2010-06-17 52 views
7

我想使用類型信息從一個數組到另一個通過繼承相關的顯式類型轉換。我的問題是,使用Type信息時,編譯器會拋出錯誤,但我的要求是根據所提供的Type信息進行動態投射。基於類型信息的動態鑄造

請幫助

class Program 
{ 
    static void Main(string[] args) 
    { 
     Parent[] objParent; 
     Child[] objChild = new Child[] { new Child(), new Child() }; 
     Type TypParent = typeof(Parent); 

     //Works when i mention the class name 
     objParent = (Parent[])objChild; 

     //Doesn't work if I mention Type info 
     objParent = (TypParent[])objChild; 
    } 
} 

class Parent 
{ 
} 

class Child : Parent 
{ 
} 

回答

12

可以動態的惟一方式是與反思。當然,你不能投objChildTypParent[] - 你正試圖將Child的數組投到Type的數組中。

你可以使用.Cast<T>()方法調用反射來實現這一點:

MethodInfo castMethod = this.GetType().GetMethod("Cast").MakeGenericMethod(typeParent); 
object castedObject = castMethod.Invoke(null, new object[] { objChild }); 

如果你需要一個非IEnumerable的類型,提出延期/靜態方法:

public static T Cast<T>(this object o) 
{ 
    return (T)o; 
}