初始化结构体在C#中的数组 [英] Initializing an Array of Structs in C#

查看:127
本文介绍了初始化结构体在C#中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能尽可能清楚地初始化结构的常量/静态数组越好?

 类SomeClass的
{    结构MYSTRUCT
    {
        公共字符串标签;
        公众诠释身份证;
    };    常量MYSTRUCT [] = MYARRAY {
          {一个,1}
          {b的,5}
          {Q,29}
    };
};


解决方案

首先,你的真正的必须有一个可变的结构?他们是邪恶的。同样的公共领域。

除此之外,我刚刚创建一个构造函数取两个数据位:

 类SomeClass的
{    结构MYSTRUCT
    {
        私人只读字符串标签;
        私人只读INT ID;        公共MYSTRUCT(字符串标签,INT ID)
        {
            this.label =标签;
            this.id = ID;
        }        公共字符串标签{{返回标签; }}
        公共字符串ID {{返回ID; }}    }    静态只读的IList<&MYSTRUCT GT; MYARRAY =新ReadOnlyCollection还<&MYSTRUCT GT;
        (新[] {
             新MYSTRUCT(一,1),
             新MYSTRUCT(B,5),
             新MYSTRUCT(Q,29)
        });
}

请注意使用 ReadOnlyCollection还的href=\"http://msdn.microsoft.com/en-us/library/ms132474.aspx\" 而不是暴露数组本身 - 这将使不变,避免问题暴露阵列直接的。 (在code表示不初始化结构的数组 - 那么它只是传递引用的构造函数 ReadOnlyCollection还<>

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

class SomeClass
{

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

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

解决方案

Firstly, do you really have to have a mutable struct? They're evil. Likewise public fields.

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 ReadOnlyCollection instead 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<>.)

这篇关于初始化结构体在C#中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆