加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – struct的const数组的初始化

发布时间:2020-12-15 18:25:31 所属栏目:百科 来源:网络整理
导读:如何对结构类型的数组进行常量初始化?例如,在C中我会做这样的事情: struct Item { int a; char const * b;};Item items[] = { { 12,"Hello" },{ 13,"Bye" },}; 我一直在寻找各种C#引用,但找不到相同的语法.有吗? 解决方法 示例代码: struct Item{ public
如何对结构类型的数组进行常量初始化?例如,在C中我会做这样的事情:
struct Item {
    int a;
    char const * b;
};
Item items[] = {
    { 12,"Hello" },{ 13,"Bye" },};

我一直在寻找各种C#引用,但找不到相同的语法.有吗?

解决方法

示例代码:
struct Item
{
    public int a;
    public string b;
};
Item[] items = {
    new Item { a = 12,b = "Hello" },new Item { a = 13,b = "Bye" }
};

引入参数化构造函数的附加选项:

struct Item
{
    public int a;
    public string b;

    public Item(int a,string b)
    {
        this.a = a;
        this.b = b;
    }
};
Item[] items = {
    new Item( 12,"Hello" ),new Item( 13,"Bye" )
};

正如@YoYo建议的那样,删除了新的[]部分.

棘手的方式(对于新物品困扰你的情况)

声明新课程:

class Items : List<Item>
{
    public void Add(int a,string b)
    {
        Add(new Item(a,b));
    }
}

然后你可以将它初始化为:

Items items = new Items {
    { 12,"Bye" }
};

您还可以应用List的.ToArray方法来获取Items数组.

Item[] items = new Items {
    { 12,"Bye" }
}.ToArray();

诀窍是基于集合初始化器(http://msdn.microsoft.com/en-us/library/bb384062.aspx):

通过使用集合初始值设定项,您不必在源代码中指定对类的Add方法的多个调用;编译器添加调用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读