代码之家  ›  专栏  ›  技术社区  ›  RobIII Lukas

需要C代码的C#等价物

  •  1
  • RobIII Lukas  · 技术社区  · 17 年前

    有人能告诉我这个C代码的C等价物吗?

    static const value_string  message_id[] = {
    
      {0x0000, "Foo"},
      {0x0001, "Bar"},
      {0x0002, "Fubar"},
      ...
      ...
      ...
    }
    
    5 回复  |  直到 17 年前
        1
  •  5
  •   GEOCHET S.Lott    17 年前
    public Enum MessageID { Foo = 0, Bar = 1, Fubar = 2 };
    

    然后,您可以使用 Enum.Format() 或 ToString()

        2
  •  1
  •   bdukes Jon Skeet    17 年前
        private static readonly IDictionary<int, string> message_id = new Dictionary<int, string>
            {
                { 0x0000, "Foo" }, 
                { 0x0001, "Bar" }
            };
    
        3
  •  1
  •   Jon Skeet    17 年前

    比如:

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

    (如果您定义了适当的 MessageId

    这是与C代码最接近的等价物,但是你应该考虑一下,根据TvasoSon的答案,EnUM是否可能是一个更合适的设计选择。

        4
  •  1
  •   Joel    17 年前
    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},
       ...
    }
    

    其中字符串是值的键。

        5
  •  0
  •   John Feminella    17 年前

    static const 类中的字段。你可以用 readonly 虽然

    如果您在本地范围内使用此选项,则可以从匿名键入中获益并执行以下操作:

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

    我喜欢 this solution 不过更好。