2012-02-19 22 views
0
List<authorinfo> aif = new List<authorinfo>(); 
for (int i = 0; i < 5; i++) 
{ 
    aif.Add(null); 
} 
aif[0] = new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844); 
aif[1] = new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972); 
aif[2] = new authorinfo("The Three Musketeers", "Alexandre", "Dumas", 1844); 
aif[3] = new authorinfo("Robinson Crusoe", "Daniel", "Defoe", 1719); 
aif[4] = new authorinfo("2001: A Space Odyssey", "Arthur", "Clark", 1968); 
//authorinfo ai = new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844); 
foreach (authorinfo i in aif) 
{ 
    Console.WriteLine(i); 
} 

さて、私が最初にforループを削除すると、なぜプログラムが起動しないのでしょうか?私はリストにnullを追加する必要があるので。リスト配列の初期化c#

私はこれを間違った方法でやっていることを知っています。私はちょうどaif [0-4]がそこに来るようにしたい、それはoutofrangeエラーを取得しないためにnullオブジェクトを追加しなければならないという意味にはなりません。

助けてください?

+0

既に与えられた良い答えに加えて、リストの容量として使用するintをリストのコンストラクタに渡すことができます。 –

答えて

5

ただ、新しいオブジェクトインスタンスを自分で追加します。

List<authorinfo> aif = new List<authorinfo>(); 
    aif.Add(new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844)); 
    //... and so on 

今、あなたはその後、インデクサーを使用して上書きプレースホルダ要素としてnullを使用している - あなたはこれを行う必要はありません(また、あなたがすべき) 。代替案として

、あなたが事前にリスト要素を知っていればあなたもcollection initializerを使用することができます。

List<authorinfo> aif = new List<authorinfo>() 
    { 
    new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844), 
    new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972), 
    new authorinfo("The Three Musketeers", "Alexandre", "Dumas", 1844) 
    }; 
+0

ありがとう、それは何かが容易だったことを知っていた。 – saturn

1

はこのようにそれを実行します。

var aif = new List<authorinfo> { 
     new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844), 
     new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972), 
     new authorinfo("The Three Musketeers", "Alexandre", "Dumas", 1844), 
     new authorinfo("Robinson Crusoe", "Daniel", "Defoe", 1719), 
     new authorinfo("2001: A Space Odyssey", "Arthur", "Clark", 1968) 
}; 

そして、あなたは

0

ときを行ってのようなインデックスを介してリスト要素にアクセスします。

var myObj = foo[4]; 

コレクションfooに少なくとも5つ(0,1,2,3,4)の要素があるとします。 forループがなければ、割り当てられていない要素にアクセスしようとしているため、範囲外のエラーが発生しています。

これを処理するにはいくつかの方法があります。最も有用なものの

var authorList = new List<authorinfo> 
{ 
new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844) 
,new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972) 
, // ..... 
}; 

ワン:あなただけの構造でリストを初期化することができ、しかし、このようなおもちゃ(宿題)問題について

List<authorinfo> aif = new List<authorinfo>(); 

aif.Add(new authorinfo("The Count of Monte Cristo", "Alexandre", "Dumas", 1844)); 
aif.Add(new authorinfo("Rendezvous with Rama", "Arthur", "Clark", 1972); 
// .... 

:最も明白にはList<>.Add()を使用することですList<>と他のコレクションは、配列ではなく動的にサイズが変更されているということです。 List<>は、すべてのノード接続を処理するリンクリストと考えてください。リンクリストのように、List<>には、ループを追加するまではノードがありません。配列内では、すべての要素への参照のための領域が前面に割り当てられているため、すぐにアクセスできますが、配列のサイズを動的に変更することはできません。