2011-08-30 174 views
0

可能重複:
How to initialize array of struct?
Initializing an Array of Structs in C#用來初始化結構數組

C#,Visual Studio 2010中

我要聲明的結構數組並初始化它的同時,但不能得到它的權利 我如何寫入默認初始化一個由結構組成的rray?

下不會去編譯通過,但顯示的是我要存檔

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

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

是否有可能在所有的想法?

回答

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

優秀,工作正常 –

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

這將是更好,如果你犯了一個構造函數,將避免鍵入屬性名稱。