【问题标题】:Initilize an array of struct [duplicate]初始化结构数组[重复]
【发布时间】:2011-08-30 13:38:13
【问题描述】:

可能的重复:
How to initialize array of struct?
Initializing an Array of Structs in C#

C#,Visual Studio 2010

我想声明一个结构数组并同时初始化它,但不能正确 如何写入默认初始化由结构组成的数组?

以下内容不会通过编译器,但会显示我想要归档的内容

    private struct PrgStrTrans_t
    {
        public int id;
        public string name;
        public string fname;
    }

    private PrgStrTrans_t[] PrgStrTrans = { {1, "hello", "there"}, {2, "Fun", thisone"}}

有可能吗?

【问题讨论】:

    标签: c# arrays struct initialization


    【解决方案1】:

    在你的结构中添加一个构造函数,并在数组的每一行放置new PrgStrTrans(...),

    像这样:

    private struct PrgStrTrans_t
    {
        public int id;
        public string name;
        public string fname;
    
        public PrgStrTrans_t(int i, string n, string f)
        {
            id = i;
            name = n;
            fname = f;
        }
    }
    
    private PrgStrTrans_t[] PrgStrTrans = {
                                              new PrgStrTrans_t(4, "test", "something"),
                                              new PrgStrTrans_t(2, "abcd", "1234")
                                          }
    

    【讨论】:

      【解决方案2】:
      private PrgStrTrans_t[] PrgStrTrans = { new PrgStrTrans_t() { id = 1, name = "hello", fname = "there"},new PrgStrTrans_t() {id = 2, name = "Fun", fname = "thisone"}};
      

      如果你创建一个构造函数会更好,这样可以避免输入属性名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多