C#将对象转换为基类列表

时间:2011-11-11 17:03:42

标签: c# casting base-class

我有以下类结构:

public class Fruit { }
public class Apple : Fruit { }

然后我使用.net框架中的一个方法,该方法从作为对象返回的类中获取属性值。所以,

// values will be of type List<Apple>
object values = someObject.GetValue()

我现在有了List类型的这个值对象,我想把它转换为Fruit类型的List。我尝试了以下但是没有用。

List<Fruit> fruits = values as List<Fruit>;

任何人都知道如何将对象转换为其基类的List?

更新:在转换时我不知道值对象是List类型我知道它应该是一个继承自Fruit的类型的List。

3 个答案:

答案 0 :(得分:5)

问题是List<Apple>List<Fruit>不是共变体。您首先必须转换为List<Apple>,然后使用LINQ的Cast方法将元素转换为Fruit

List<Fruit> fruits = values is List<Apple> ? 
    (values as List<Apple>).Cast<Fruit>().ToList() :
    new List<Fruit>();

如果您不提前知道类型并且不需要修改列表(并且您使用的是C#4.0),则可以尝试:

IEnumerable<Fruit> fruits = values as IEnumerable<Fruit>;

或者,我想,如果你需要一个List:

List<Fruit> fruits = (values as IEnumerable<Fruit>).ToList();

答案 1 :(得分:2)

你应该试试linq cast method。 Cast方法将返回您正在投射的类型的IEnumerable ......

   List<Fruit> fruits = null;
   if ( values is List<Apples> ) 
     fruits = ((List<Apples>)values).Cast< fruits >.ToList();

答案 2 :(得分:1)

既然你说你知道这个对象是一个水果列表,但你不知道它是哪个水果,你可以这样做:

List<Fruit> fruits = ((IEnumerable)values).Cast<Fruit>().ToList();

如果你使用的是.NET 4(不包括Silverlight 4),你可以使用Justin Niessner的解决方案:

List<Fruit> fruits = ((IEnumerable<Fruit>)values).ToList();

最后,如果有一个调用网站,其中已知水果的静态类型(Apple或其他),则可以使用通用解决方案。这意味着要更改代码,以便您不再使用反射获取值。

另一种通用方法是创建泛型方法并通过在对象上调用GetType()来在运行时构造它,但这可能是治愈比疾病更糟的情况。