基于类型信息的动态投射

Abr*_*mJP 7 c# casting

我想使用从一个数组到另一个数组的类型信息进行显式转换,这通过继承相关.我的问题是,在使用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
{
}
Run Code Online (Sandbox Code Playgroud)

Fem*_*ref 13

你可以动态投射的唯一方法是使用反射.当然你不能强制objChild转换TypParent[]- 你试图将数组Child转换为数组Type.

您可以使用使用.Cast<T>()反射调用的方法来实现此目的:

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

如果您需要一个非IEnumerable类型,请创建扩展/静态方法:

public static T Cast<T>(this object o)
{
    return (T)o;
}
Run Code Online (Sandbox Code Playgroud)