我想使用类型信息从一个数组到另一个数组进行显式转换,这是通过继承来关联的。我的问题是,当使用类型信息进行转换时,编译器会抛出错误,但我的要求是基于提供的类型信息进行动态转换。
请帮帮忙
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
{
}发布于 2010-06-17 23:02:20
您可以动态转换的唯一方法是使用反射。当然,您不能将objChild转换为TypParent[] -您正在尝试将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;
}https://stackoverflow.com/questions/3062807
复制相似问题