2013-05-23 13 views
7

ben şu varC# listesini ilan ve değerler kod

var list = new List<IMyCustomType>(); 
list.Add(new MyCustomTypeOne()); 
list.Add(new MyCustomTypeTwo()); 
list.Add(new MyCustomTypeThree()); 

bu tabii çalışır liste bir satır kullanarak doldurmak, ama listenin ilan ve değerler bir ifade kullanarak doldurma yok nasıl acaba ediyorum ?

Teşekkür

+2

http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx -1 Başlatıcı toplama kullanımı. ;) – Leri

+0

Eh, 'var list = new List (); list.Add (yeni MyCustomTypeOne()); list.Add (yeni MyCustomTypeTwo()); list.Add (yeni MyCustomTypeThree()); 'bir satırda. Yoksa sen mi demek istedin? –

+0

@DavidHeffernan :) bir açıklama, ofchurse – user1765862

cevap

11
var list = new List<IMyCustomType>{ 
    new MyCustomTypeOne(), 
    new MyCustomTypeTwo(), 
    new MyCustomTypeThree() 
}; 

Düzenleme: Asker "tek deyimi" ile "bir satır" olarak değiştirildi ve bu daha hoş görünüyor.

kullanabilirsiniz
+0

+1 hiçbir şey eklemek :-) – Kooki

2

bir collection initializor:

Eğer bir satırda istediğiniz Tam olarak emin
var list = new List<IMyCustomType>() { new MyCustomTypeOne(), new MyCustomTypeTwo(), new MyCustomTypeThree() }; 
0
var list = new List<IMyCustomType>{ new MyCustomTypeOne(), new MyCustomTypeTwo() }; 
8
var list = new List<IMyCustomType> 
{ 
    new MyCustomTypeOne(), 
    new MyCustomTypeTwo(), 
    new MyCustomTypeThree() 
}; 

değil mi?

+0

sadece merak ediyorum, hepsi bu – user1765862

+1

Anlaştık. Bir hatta korkunç görünüyor. Diğer tüm cevaplarda kaydırma çubuğuna bakın. ;) –

+0

Küçük bir yazım hatası, yeni MyCustomTypeThree() 'dan sonraki virgül orada olmamalıdır. – hattenn

3

belgeleri kullanmayan için

var list = new List<IMyCustomType> 
{ 
    new MyCustomTypeOne(){Properties should be given here}, 
    new MyCustomTypeTwo(){Properties should be given here}, 
    new MyCustomTypeThree(){Properties should be given here}, 
}