c# - 在 C# 中初始化结构数组

标签 c# arrays struct

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

class SomeClass
{

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

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

最佳答案

首先,您真的必须要有一个可变结构吗?他们几乎总是一个坏主意。同样是公共(public)领域。在某些非常偶然的情况下,它们是合理的(通常两个部分在一起,如 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 的使用而不是暴露数组本身——这将使它不可变,避免 the problem exposing arrays directly . (代码显示确实初始化了一个结构数组 - 然后它只是将引用传递给 ReadOnlyCollection<> 的构造函数。)

关于c# - 在 C# 中初始化结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/309496/

相关文章:

c# - DataGridViewComboBoxColumn - 必须单击单元格两次才能显示组合框

c# - 如何在不知道元素的情况下循环所有 XML 属性

php - 如果未找到 array_search 查询

c - C语言如何将文本读入数组

c++ - vector::erase() 也删除结构的成员 vector

c# - IDE 下划线自定义属性

c# - 从 C# 源文件中提取属性名称

java - 访问单独类中的数组时出现问题

c++ - 指针类 C++

c - p 是一个指向结构的指针,所有这些代码片段都做了什么?