2011-06-08 49 views
0

我敢肯定,這已經在這裏已經問過,但我無法找到答案...
在C中有這樣的:數組創建C#中的常量

#define COMMAND_ARGUMENTS_SIZE (3) 
typedef struct 
{ 
    unsinged char opcode; 
    unsigned char arguments[COMMAND_ARGUMENTS_SIZE]; 
} Command; 

在我們希望C#像這樣:

struct Command 
{ 
    byte opcode; 
    byte arguments[...]; 
}  

陣列大小處於不穩定狀態,我們有它們在幾個文件中使用。我們想保留#define(但我們知道我們不能......)。這是一個端口,我們不打算進行重大改寫。

回答

2

您可以定義常量的實用工具類,以舉辦 「定義」 般在C#指令:

public static class Constants 
{ 
    public const int CommandArgumentsSize = 3; 
} 

struct Command 
{ 
    byte opcode; 
    byte[] arguments = new byte[Constants.CommandArgumentsSize]; 
} 
+0

這似乎使生活更簡單..但是你需要一個字節[]爲'參數'。 – Gio 2011-06-08 22:37:27

+0

另外,你不需要爲常量的類... MS只是建議... – Gio 2011-06-08 22:40:18

+0

你不需要*的類,但我認爲它有助於保持地方。並感謝字節/字節[]類型,我已經修復它。 – carlosfigueira 2011-06-08 22:46:07

4

將該類型標記爲「不安全」並使用fixed size buffer

unsafe struct Command 
{ 
    const int CommandArgumentsSize = 3; 
    byte opcode; 
    fixed byte arguments[CommandArgumentsSize]; 
} 

「固定」聲明和「固定」聲明之間很容易混淆。 See my article on the subject if this is confusing.

或者,如果你只有他們三個人的話,我會傾向於:

struct Command 
{ 
    byte opcode; 
    byte arg1; 
    byte arg2; 
    byte arg3; 
} 

易peasy,沒有瘋狂的三分球瞎搞。如果只有三個,這是一個很好的解決方案;如果它是一個1000字節的結構,那麼可能不會那麼熱。

+0

'fixed'必須在類型之前,而不是在之後。 – svick 2011-06-08 22:32:21

+0

我對'固定'並不感到激動,因爲它給我帶來了'不安全',然後我不得不傳播'鏈條',現在簽署支票的那個人很有趣地看着我,因爲他想讓它完成。 – Gio 2011-06-08 22:33:52

0

使用一個靜態類

static class Constants 
{ 
    public const int DEFAULT_ARRAY_SIZE = 20; 
} 

它通常是一個更好的主意來封裝這些知識,但是這樣的事情不會是可怕的,只要你不把以上幾個常數更在那裏。

0

代替#define在C#中使用public const

struct Command { 
    public const int ArgumentSize = 3; 
    byte opcode; 
    byte[] arguments; 
} 

注意:你有「分配」字節數組。我會使用預先分配的類:

class Command { 
    public const int ArgumentSize = 3; 
    public byte opcode; 
    public byte[] arguments = new byte[ArgumentSize]; 
} 
0

你可以這樣做:

unsafe struct Command 
{ 
    const int CommandArgumentSize = 3; 

    byte opcode; 
    fixed byte arguments[CommandArgumentSize]; 
} 

你必須允許不安全的代碼在編譯器來做到這一點。

如果您只想使用它與某些非託管代碼進行通信,則使用[MarshalAs(UnmanagedType.ByValArray)]也應該這樣做。