开发者

Initilize an array of struct [duplicate]

This question already has answers here: Cl开发者_开发问答osed 11 years ago.

Possible Duplicates:

How to initialize array of struct?

Initializing an Array of Structs in C#

C#, Visual studio 2010

I want declare an array of struct and initialize it on the same time but can not get it right How do i write to default initialize an array consisting of structs ?

The following wont go through the compiler but show the idea of what I want to archive

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

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

Is it possible at all ?


Add a constructor to your struct, and put new PrgStrTrans(...), on each line of the array.

Like this:

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


private PrgStrTrans_t[] PrgStrTrans = { new PrgStrTrans_t() { id = 1, name = "hello", fname = "there"},new PrgStrTrans_t() {id = 2, name = "Fun", fname = "thisone"}};

It would be better if you made a constructor, that would avoid typing the property names.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜