在 C# 中初始化结构数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/309496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 22:39:21  来源:igfitidea点击:

Initializing an Array of Structs in C#

c#arraysstruct

提问by Adam Tegen

How can I initialize a const / static array of structs as clearly as possible?

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

class SomeClass
{

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

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

采纳答案by Jon Skeet

Firstly, do you reallyhave to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with ValueTuple) but they're pretty rare in my experience.

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

Other than that, I'd just create a constructor taking the two bits of data:

除此之外,我只是创建一个带有两位数据的构造函数:

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)
        });
}

Note the use of ReadOnlyCollectioninstead of exposing the array itself - this will make it immutable, avoiding the problem exposing arrays directly. (The code show does initialize an array of structs - it then just passes the reference to the constructor of ReadOnlyCollection<>.)

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

回答by Winston Smith

Are you using C# 3.0? You can use object initializers like so:

你在使用 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" }
            };

回答by Ali Ers?z

You cannot initialize reference types by default other than null. You have to make them readonly. So this could work;

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

    readonly MyStruct[] MyArray = new MyStruct[]{
      new MyStruct{ label = "a", id = 1},
      new MyStruct{ label = "b", id = 5},
      new MyStruct{ label = "c", id = 1}
    };

回答by Paul Sonier

I'd use a static constructor on the class that sets the value of a static readonly array.

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

public class SomeClass
{
   public readonly MyStruct[] myArray;

   public static SomeClass()
   {
      myArray = { {"foo", "bar"},
                  {"boo", "far"}};
   }
}

回答by Shreevardhan

Change constto static readonlyand initialise it like this

更改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 }
};