2011-08-30 3 views
0

Doublons possibles:
How to initialize array of struct?
Initializing an Array of Structs in C#Initilize un tableau de struct

C#, Visual Studio 2010

Je veux déclarer un tableau de struct et l'initialiser sur la même temps, mais ne peut pas le faire correctement Comment puis-je écrire à par défaut initialiser un rayer composé de structures?

qui suit wont go par le compilateur, mais montrer l'idée de ce que je veux archiver

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

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

Est-il possible?

Répondre

1

Ajoutez un constructeur à votre structure et placez new PrgStrTrans(...), sur chaque ligne du tableau.

Comme ceci:

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

Excellent, fonctionne bien –

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

Il serait mieux si vous avez fait un constructeur, cela éviterait de taper les noms de propriétés.

Questions connexes