54

如何尽可能清楚地初始化 const / static 结构数组?

class SomeClass
{

    struct MyStruct
    {
        public string label;
        public int id;
    };

    const MyStruct[] MyArray = {
          {"a", 1}
          {"b", 5}
          {"q", 29}
    };
};
4

5 回答 5

57

首先,你真的必须有一个可变结构吗?他们几乎总是一个坏主意。公共领域也是如此。有一些非常偶然的情况下它们是合理的(通常两个部分一起,如ValueTuple),但在我的经验中它们非常罕见。

除此之外,我只需要创建一个构造函数来获取这两位数据:

class SomeClass
{

    struct MyStruct
    {
        private readonly string label;
        private readonly int id;

        public MyStruct (string label, int id)
        {
            this.label = label;
            this.id = id;
        }

        public string Label { get { return label; } }
        public string Id { get { return id; } }

    }

    static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
        (new[] {
             new MyStruct ("a", 1),
             new MyStruct ("b", 5),
             new MyStruct ("q", 29)
        });
}

请注意使用ReadOnlyCollection而不是公开数组本身 - 这将使其不可变,避免直接公开数组的问题。(代码显示确实初始化了一个结构数组 - 然后它只是将引用传递给 . 的构造函数ReadOnlyCollection<>。)

于 2008-11-21T17:18:47.370 回答
28

您使用的是 C# 3.0 吗?您可以像这样使用对象初始值设定项:

static MyStruct[] myArray = 
            new MyStruct[]{
                new MyStruct() { id = 1, label = "1" },
                new MyStruct() { id = 2, label = "2" },
                new MyStruct() { id = 3, label = "3" }
            };
于 2008-11-21T17:22:16.440 回答
6

默认情况下,您不能初始化 null 以外的引用类型。您必须将它们设为只读。所以这可以工作;

    readonly MyStruct[] MyArray = new MyStruct[]{
      new MyStruct{ label = "a", id = 1},
      new MyStruct{ label = "b", id = 5},
      new MyStruct{ label = "c", id = 1}
    };
于 2008-11-21T17:24:27.840 回答
3

像这样更改conststatic readonly初始化它

static readonly MyStruct[] MyArray = new[] {
    new MyStruct { label = "a", id = 1 },
    new MyStruct { label = "b", id = 5 },
    new MyStruct { label = "q", id = 29 }
};
于 2017-10-24T18:13:01.820 回答
-3

我会在设置静态只读数组的值的类上使用静态构造函数。

public class SomeClass
{
   public readonly MyStruct[] myArray;

   public static SomeClass()
   {
      myArray = { {"foo", "bar"},
                  {"boo", "far"}};
   }
}
于 2008-11-21T17:41:25.873 回答