2011-01-11 20 views
34

C# (.Net 2.0) 'da yansıyan türden genel bir nesne oluşturmak mümkün mü?C# genel örnek Yansıtılan türden bir liste

void foobar(Type t){ 
    IList<t> newList = new List<t>(); //this doesn't work 
    //... 
} 

Tür, t, çalışma zamanına kadar bilinmemektedir.

+0

Derleme zamanında türünü bilmediğiniz bir listeyle ne yapmayı düşünüyorsunuz? – dtb

+1

Bunu jenerik bir işlev olarak yazabilirsiniz: void foobar () {IList newList = yeni Liste (); } ' – Juliet

+1

Kötü bir şekilde daha büyük bir sorunun üstesinden gelmenin bir sonucu olarak bunun bir kod kokusu olabileceğini hissettim. –

cevap

102

bu deneyin: instance ne

Şimdi
void foobar(Type t) 
{ 
    var listType = typeof(List<>); 
    var constructedListType = listType.MakeGenericType(t); 

    var instance = Activator.CreateInstance(constructedListType); 
} 

yapmalı?

// Now you have a list - it isn't strongly typed but at least you 
// can work with it and use it to some degree. 
var instance = (IList)Activator.CreateInstance(constructedListType); 
+6

+1 için "typeof (List <>)", I Bunu daha önce görmemiştim. –

+0

, .NET framework 2.0'da var mı ?! –

+0

@sprocketonline: "var" bir C# 3 özelliğidir, bu yüzden C# 2 kullanıyorsanız değişkenlerinizi açık bir şekilde bildirmeniz gerekir. Eski iyi olmayan genel destekli arayüzleri hatırlamak için –

0

Sen kullanabilirsiniz: Eğer listenizin içeriğinin türünü bilmiyorum beri muhtemelen yapabileceği en iyi şey sadece bir object Eğer başka bir şey var, öyle ki bir IList olarak instance Döküm olacaktır Bu tür işlemler için MakeGenericType.

Belgeler için bkz. here ve here.

6
static void Main(string[] args) 
{ 
    IList list = foobar(typeof(string)); 
    list.Add("foo"); 
    list.Add("bar"); 
    foreach (string s in list) 
    Console.WriteLine(s); 
    Console.ReadKey(); 
} 

private static IList foobar(Type t) 
{ 
    var listType = typeof(List<>); 
    var constructedListType = listType.MakeGenericType(t); 
    var instance = Activator.CreateInstance(constructedListType); 
    return (IList)instance; 
} 
+0

+1 – leppie

İlgili konular