Array creation with constants in c#
I'm sure this has been asked here already but I can't locate the answer...
In c we have this:#define COMMAND_ARGUMENTS_SIZE (3)
typedef struct
{
unsinged char opcode;
unsigned char arguments[COMMAND_ARGUMENTS_SIZE];
} Command;
In c# we'd like this:
struct Command
{
byte opcode;
byte arguments[...];
}
The array sizes are in a state of flux and we have them used across several files. We'd like to keep the #define (but we know开发者_开发问答 we can't....). This is a port and we're not about to do major rewrites.
Mark the type as "unsafe" and use a fixed size buffer.
unsafe struct Command
{
const int CommandArgumentsSize = 3;
byte opcode;
fixed byte arguments[CommandArgumentsSize];
}
It is easy to get confused between the "fixed" declaration and the "fixed" statement. See my article on the subject if this is confusing.
Alternatively, if you only have three of them then I'd be inclined to:
struct Command
{
byte opcode;
byte arg1;
byte arg2;
byte arg3;
}
Easy peasy, no messing around with crazy pointers. If there are only three of them, that's a good solution; if it's a 1000 byte struct then that might not be so hot.
You can define a constants utility class to hold the "define"-like directives in C#:
public static class Constants
{
public const int CommandArgumentsSize = 3;
}
struct Command
{
byte opcode;
byte[] arguments = new byte[Constants.CommandArgumentsSize];
}
Use a static class
static class Constants
{
public const int DEFAULT_ARRAY_SIZE = 20;
}
It's generally a better idea to encapsulate such knowledge but something like this would not be awful as long as you don't put more than a few constants in there.
Instead of #define
use a public const
in C#
struct Command {
public const int ArgumentSize = 3;
byte opcode;
byte[] arguments;
}
Note: that you have "allocate" the byte array. I would use a class that preallocates:
class Command {
public const int ArgumentSize = 3;
public byte opcode;
public byte[] arguments = new byte[ArgumentSize];
}
You can do this:
unsafe struct Command
{
const int CommandArgumentSize = 3;
byte opcode;
fixed byte arguments[CommandArgumentSize];
}
You have to allow unsafe code in your compiler to do this.
If you only want to use it for communication with some unmanaged code, using [MarshalAs(UnmanagedType.ByValArray)]
should do the trick too.
精彩评论