我想将基类实例列表中的信息投影到派生类实例列表中,但我一直在运行异常。以下是我尝试做的一个例子......我该如何让它发挥作用?
以下代码在http://ideone.com/CaXQS处,如果有帮助的话......提前感谢!
using System;
using System.Collections.Generic;
namespace AddingReversedNumbers
{
public class MyDerivedClass : MyBaseClass, IMyInterface
{
public int InterfaceProperty { get; set; }
public int DerivedClassProperty { get; set; }
public List<int> DerivedClassList { get; set; }
}
public class MyBaseClass
{
public int BaseClassProperty { get; set; }
}
public interface IMyInterface
{
int InterfaceProperty { get; set; }
}
class Program
{
static void Main()
{
//// This code works just fine.
//var derivedList = new List<MyDerivedClass>();
//derivedList.Add(new MyDerivedClass { BaseClassProperty = 10, DerivedClassProperty = 20, InterfaceProperty = 30 });
//derivedList.Add(new MyDerivedClass { BaseClassProperty = 20, DerivedClassProperty = 40, InterfaceProperty = 60 });
//var baseList = derivedList.ConvertAll(x => (MyBaseClass)x);
// This code breaks when ConvertAll() is called.
var baseList = new List<MyBaseClass>();
baseList.Add(new MyBaseClass{ BaseClassProperty = 10 });
baseList.Add(new MyBaseClass{ BaseClassProperty = 20 });
var derivedList = baseList.ConvertAll(x => (MyDerivedClass)x);
}
}
}
答案 0 :(得分:5)
在您的ConvertAll
代码中,您只是投射。您不能将基类实例强制转换为派生类实例。例如,您希望将object
投射到FileStream
做什么?它会引用哪个文件?
如果您想在ConvertAll
投影中创建新对象,请执行以下操作:
var derivedList = baseList.ConvertAll
(x => new MyDerivedClass { BaseClassProperty = x.BaseClassProperty });