2010-12-15 46 views
2

我怎樣才能創建一個實例,從通用繼承的類型,靜態地將它轉換爲它的基類型有沒有辦法在實例化從泛型繼承的類型時不使用動態方法?

foreach(Type t in x.ChildType.Assembly.GetTypes()) 
{ 
    if (t.BaseType.IsGenericType) 
    { 
     if (t.BaseType.GetGenericTypeDefinition() == typeof(ClassMapExt<>)) 
     { 
      if (t.BaseType.GetGenericArguments()[0] == x.ChildType) 
      { 
       // t is BonusMap. BonusMap is declared as: 
       // class BonusMap : ClassMapExt<Bonus> 
       dynamic bz = Activator.CreateInstance(t); 

       // the last line is analogous to: 
       // var bz = new BonusMap(); 

       // statically casting it doesn't work 
       // var bz = (ClassMapExt<>) Activator.CreateInstance(t); 

       foreach (IManyToOneMappingProvider imt1 in bz.ExtReference) 

回答

2

通常情況下做到這一點的辦法是包括非通用的API,在那裏(或許具有明確實現)。然後你只需轉到非通用接口。

不太一樣,但有點像:

Type itemType = ...; 
IList list = (IList)Activator.CreateInstance(
    typeof(List<>).MakeGenericType(itemType)); 
list.Add(...); 
相關問題