谁能告诉我这个 C 代码的 C# 等价物吗?
static const value_string message_id[] = {
{0x0000, "Foo"},
{0x0001, "Bar"},
{0x0002, "Fubar"},
...
...
...
}
谁能告诉我这个 C 代码的 C# 等价物吗?
static const value_string message_id[] = {
{0x0000, "Foo"},
{0x0001, "Bar"},
{0x0002, "Fubar"},
...
...
...
}
public Enum MessageID { Foo = 0, Bar = 1, Fubar = 2 };
Enum.Format()
然后,您可以使用or获得“字符串”版本ToString()
。
就像是:
MessageId[] messageIds = new MessageId[] {
new MessageId(0x0000, "Foo"),
new MessageId(0x0001, "Bar"),
new MessageId(0x0002, "Fubar"),
...
};
(您在其中定义适当的MessageId
构造函数。)
这是与 C 代码最接近的等价物 - 但您当然应该考虑根据 tvanfosson 的答案的枚举是否可能是更合适的设计选择。
private static readonly IDictionary<int, string> message_id = new Dictionary<int, string>
{
{ 0x0000, "Foo" },
{ 0x0001, "Bar" }
};
private const value_string message_id[] = {
new value_string() { prop1 = 0x0000, prop2 = "Foo"},
new value_string() { prop1 = 0x0001, prop2 = "Bar"},
new value_string() { prop1 = 0x0002, prop2 = "Fubar"},
...
...
...
}
或者更好的是,如果您像字典一样使用它:
private const Dictionary<string, int> message_id = {
{"Foo", 0},
{"Bar", 1},
{"Fubar", 2},
...
}
其中字符串是您获取值的关键。
不会有完全匹配的。C# 不允许类static
中的const
字段。不过,您可以使用readonly
.
如果您在本地范围内使用它,那么您可以获得匿名输入的好处并执行以下操作:
var identifierList = new[] {
new MessageIdentifier(0x0000, "Foo"),
new MessageIdentifier(0x0001, "Bar"),
new MessageIdentifier(0x0002, "Fubar"),
...
};
不过,我更喜欢这个解决方案。