C# Dynamic Cast with Reflection and Lists

2019-07-19 00:41发布

since yesterday i'm working on a problem and i don't get it yet...

I've got a class with many Methods and decide in Runtime wich Method has to be called. Every of this Methods returns a List with Elements from my Businessobjects.

My Class looks this way:

public class ReflectiveClass {

    public List<BO1> DoSomethingWithBO1(int param){
        List<BO1> list = new List<BO1>();
        //....
        return list;
    }

    public List<BO2> DoSomethingWithBO2(int param){
        List<BO2> list = new List<BO2>();
        //....
        return list;
    }

    public void Process(){
        //...get MethodInfo and so on
        List<object> myReturnValue = (List<object>)methodInfo.Invoke(this, new object[]{param});
        // here comes the Exception
    }
}

So, at Invoking the Method i got a InvalidCastException and the Debugger told me he could not Cast from

System.Collections.Generic.List`1[BO1]

to

System.Collections.Generic.List`1[System.Object]

I wonder why this doesn't work. I thougt if i use a List every Object could be in this List.

I've even tried it with List but same behaviour.

Is it possible to read reflective the Type of the Return-Value of a Method? And can i then create a Generic List with this Returnvalue and cast to this List? This would be wonderfull.

Greetings and many Thanks for your Help! Benni

7条回答
再贱就再见
2楼-- · 2019-07-19 01:36

You can use this :

object myReturnValue = mi.Invoke(this, new object[] { });
MethodInfo miToList = typeof(Enumerable).GetMethod("ToList");
MethodInfo miListObject = miToList.MakeGenericMethod(new[] { typeof(object) });
List<object> listObject = (List<object>)miListObject.Invoke(myReturnValue, new object [] { myReturnValue });
查看更多
登录 后发表回答