【发布时间】:2009-03-19 16:07:49
【问题描述】:
谁能告诉我这个 C 代码的 C# 等价物吗?
static const value_string message_id[] = {
{0x0000, "Foo"},
{0x0001, "Bar"},
{0x0002, "Fubar"},
...
...
...
}
【问题讨论】:
标签: c# arrays initialization
谁能告诉我这个 C 代码的 C# 等价物吗?
static const value_string message_id[] = {
{0x0000, "Foo"},
{0x0001, "Bar"},
{0x0002, "Fubar"},
...
...
...
}
【问题讨论】:
标签: c# arrays initialization
public Enum MessageID { Foo = 0, Bar = 1, Fubar = 2 };
然后你可以使用Enum.Format()或ToString()获取“字符串”版本。
【讨论】:
private static readonly IDictionary<int, string> message_id = new Dictionary<int, string>
{
{ 0x0000, "Foo" },
{ 0x0001, "Bar" }
};
【讨论】:
类似:
MessageId[] messageIds = new MessageId[] {
new MessageId(0x0000, "Foo"),
new MessageId(0x0001, "Bar"),
new MessageId(0x0002, "Fubar"),
...
};
(您在其中定义了适当的MessageId 构造函数。)
这是与 C 代码最接近的等价物 - 但您当然应该考虑根据 tvanfosson 的回答使用枚举是否可能是更合适的设计选择。
【讨论】:
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# 不允许在类中的 const 字段上使用 static。不过,您可以使用readonly。
如果您在本地范围内使用它,那么您可以获得匿名输入的好处并执行以下操作:
var identifierList = new[] {
new MessageIdentifier(0x0000, "Foo"),
new MessageIdentifier(0x0001, "Bar"),
new MessageIdentifier(0x0002, "Fubar"),
...
};
不过,我更喜欢this solution。
【讨论】: