C#动态转换与反思和列表 [英] C# Dynamic Cast with Reflection and Lists

查看:157
本文介绍了C#动态转换与反思和列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从昨天起我工作的一个问题,我不明白这一点尚未...

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

我有一类具有许多方法,并决定在运行时至极方法被调用。 。每到这个方法返回从我的BusinessObjects元素的列表

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



所以,在调用方法我得到了
InvalidCastException的
和调试器告诉我,他无法从

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]

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

我不知道为什么这是行不通的。我thougt如果我使用列表中的每个对象可以在此列表中。

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

推荐答案

显然 BO1 派生自对象,你可以不投列表<衍生> 列表<基地> 。假设我们有:

Obviously BO1 derives from Object, and you can't cast List<Derived> to List<Base>. Suppose we have:

List<Apple> apples = AListOfApples();
List<Fruit> fruits = (List<Fruit>)apples;  //suppose it's valid to cast
fruits.Add(new Orange());  //Of course we can add an Orange to the list of Fruit
//Now you can see the list of Apple has an Orange in it!!

您可以使用的IEnumerable< T> 而不是

这篇关于C#动态转换与反思和列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆