1

谁能告诉我这个 C 代码的 C# 等价物吗?

static const value_string  message_id[] = {

  {0x0000, "Foo"},
  {0x0001, "Bar"},
  {0x0002, "Fubar"},
  ...
  ...
  ...
}
4

5 回答 5

5
public Enum MessageID { Foo = 0, Bar = 1, Fubar = 2 };

Enum.Format()然后,您可以使用or获得“字符串”版本ToString()

于 2009-03-19T16:09:58.907 回答
1

就像是:

MessageId[] messageIds = new MessageId[] {
    new MessageId(0x0000, "Foo"),
    new MessageId(0x0001, "Bar"),
    new MessageId(0x0002, "Fubar"),
    ...
};

(您在其中定义适当的MessageId构造函数。)

这是与 C 代码最接近的等价物 - 但您当然应该考虑根据 tvanfosson 的答案的枚举是否可能是更合适的设计选择。

于 2009-03-19T16:10:37.983 回答
1
    private static readonly IDictionary<int, string> message_id = new Dictionary<int, string>
        {
            { 0x0000, "Foo" }, 
            { 0x0001, "Bar" }
        };
于 2009-03-19T16:12:31.583 回答
1
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},
   ...
}

其中字符串是您获取值的关键。

于 2009-03-19T16:12:59.537 回答
0

不会有完全匹配的。C# 不允许类static中的const字段。不过,您可以使用readonly.

如果您在本地范围内使用它,那么您可以获得匿名输入的好处并执行以下操作:

var identifierList = new[] {
    new MessageIdentifier(0x0000, "Foo"),
    new MessageIdentifier(0x0001, "Bar"),
    new MessageIdentifier(0x0002, "Fubar"),
    ...
};

不过,我更喜欢这个解决方案

于 2009-03-19T16:12:09.867 回答