我想將基礎類實例列表中的信息投影到派生類實例列表中,但我一直在投入轉換異常。這是我想要做的一個例子...我如何使它工作?C#和基礎派生類Casting
以下代碼在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);
}
}
}
內的項目'baseList'的類型MyDerivedClass'的'沒有,所以演員總是失敗......你究竟想完成什麼? – 2012-08-10 19:52:12
我認爲這更好地描述爲'上傳'。是否有理由不直接將DerivedClass的實例添加到列表? –
mclark1129
2012-08-10 19:53:05
對於列表中的每個項目,我想使用MyBaseClass中的所有信息填充MyDerivedClass的一個新實例。 – 2012-08-10 19:53:34