【问题标题】:C# equivalent for C code needed需要 C 代码的 C# 等效项
【发布时间】:2009-03-19 16:07:49
【问题描述】:

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

static const value_string  message_id[] = {

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

【问题讨论】:

    标签: c# arrays initialization


    【解决方案1】:
    public Enum MessageID { Foo = 0, Bar = 1, Fubar = 2 };
    

    然后你可以使用Enum.Format()或ToString()获取“字符串”版本。

    【讨论】:

    • 我其实更喜欢 bdukes 解决方案,但那是因为无论如何我都需要字典中的数据。
    • 没问题。它看起来就像我会使用枚举的东西——没有任何其他上下文。您可能还想考虑从配置文件中加载它,而不是在代码中定义它。这样您就不必重新编译您的应用程序来添加另一个消息 ID。
    • 我知道;但就我而言,我可以安全地对其进行硬编码,因为我正在“剖析”一个不会改变的协议。如果是这样,我需要修改的不仅仅是 consts ;)
    【解决方案2】:
        private static readonly IDictionary<int, string> message_id = new Dictionary<int, string>
            {
                { 0x0000, "Foo" }, 
                { 0x0001, "Bar" }
            };
    

    【讨论】:

      【解决方案3】:

      类似:

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

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

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

      【讨论】:

        【解决方案4】:
        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】:

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

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

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

          不过,我更喜欢this solution。

          【讨论】:

            猜你喜欢
            • 2015-09-14
            • 1970-01-01
            • 2014-03-21
            • 2011-03-10
            • 2011-12-18
            • 1970-01-01
            • 2015-03-26
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多