开发者

Dynamic Casting based on Type information

开发者 https://www.devze.com 2023-01-03 16:00 出处:网络
I want to do an explicit cast using Type information from one array to another which is related by inheritance. My problem is that while casting using Type informationthe compiler throws error, but my

I want to do an explicit cast using Type information from one array to another which is related by inheritance. My problem is that while casting using Type information the compiler throws error, but my requirement is to dynamically cast based on the Type information provided.

Please Help

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
{
}


The only way you can cast dynamically is with reflection. Of course you can't cast objChild to TypParent[] - you are trying to cast an array of Child to an array of Type.

You could use the .Cast<T>() method called with reflection to achieve this:

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

If you need one for non-IEnumerable types, make an extension/static method:

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

精彩评论

暂无评论...
验证码 换一张
取 消