我需要一个抽象类,其中包含一个方法来返回从基类或接口(interface)派生的项目列表。我的代码如下:
public abstract class Template
{
//this should return the data to be used by the template
public abstract List GetDataSource(string sectionName);
}
然后我有一个派生数据类,专门与派生模板类一起使用:
public class DerivedDataClass : BaseDataClass
{
//some properties specific to the derived class
}
然后我就有了继承抽象类的主要派生模板类。在这里我想返回 DerivedDataClass 的列表。
public class DerivedTemplate : Template
{
public override List GetDataSource(string sectionName)
{
List data = new List();
//add some stuff to the list
return data;
}
}
当我尝试返回该列表时,出现“无法将类型 System.Collections.Generic.List 隐式转换为 System.Collections.Generic.List”。
我意识到这些类型之间没有直接转换,但我不确定如何实现这一点。将来会有更多的派生模板类和派生数据类,我将需要使用 GetDataSource 函数来获取数据项列表。 我想我想得太多了,但我已经在墙边呆了一段时间了,不确定我应该朝哪个方向走。
List
Và T
不相关的协变体,所以List
无法转换为 List
.
想象一下List
将是协变的。你可以这样写:
List bases = new List();
bases.Add(new Derived2());
这里Derived2
VàDerived1
是不同的派生类。这是一个错误,所以Danh sách
Và T
不存在协变关系.
那么,你能做什么?
IEnumerable
是协变的
var bases = new List(deriveds.AsEnumerable());
LINQ 的 Cast
var bases = deriveds.Cast()
.ToList();
Tôi là một lập trình viên xuất sắc, rất giỏi!