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(但我们知道我们不能......)。这是一个移植,我们不打算进行重大重写。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
将类型标记为“不安全”并使用固定大小缓冲区。
“固定”声明和“固定”语句很容易混淆。 如果这令人困惑,请参阅我关于该主题的文章。
或者,如果您只有其中三个,那么我会倾向于:
轻松简单,不要乱搞疯狂的指针。如果只有三个,这是一个很好的解决方案;如果它是一个 1000 字节的结构,那么可能不会那么热。
Mark the type as "unsafe" and use a fixed size buffer.
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:
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.
您可以定义一个常量实用程序类来保存 C# 中的类似“define”的指令:
You can define a constants utility class to hold the "define"-like directives in C#:
使用静态类封装
这些知识通常是一个更好的主意,但是只要您不在那里放置超过几个常量,这样的事情就不会很糟糕。
Use a static class
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.
在 C# 中使用
public const
代替#define
注意:您已经“分配”了字节数组。我会使用一个预分配的类:
Instead of
#define
use apublic const
in C#Note: that you have "allocate" the byte array. I would use a class that preallocates:
您可以这样做:
您必须允许编译器中的不安全代码才能执行此操作。
如果您只想使用它与某些非托管代码进行通信,那么使用
[MarshalAs(UnmanagementType.ByValArray)]
也可以达到目的。You can do this:
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.