我需要一个抽象类,其中包含一个方法来返回从基类或接口派生的项目列表。我的代码如下:
public abstract class Template
{
//this should return the data to be used by the template
public abstract List<BaseDataClass> GetDataSource(string sectionName);
}
然后,我有一个派生数据类,专门与派生模板类一起使用:
public class DerivedDataClass : BaseDataClass
{
//some properties specific to the derived class
}
然后我有继承抽象类的主要派生模板类。在这里我想返回 DerivedDataClass 的列表。
public class DerivedTemplate : Template
{
public override List<BaseDataClass> GetDataSource(string sectionName)
{
List<DerivedDataClass> data = new List<DerivedDataClass>();
//add some stuff to the list
return data;
}
}
当我尝试返回该列表时,我收到“无法将类型 System.Collections.Generic.List 隐式转换为 System.Collections.Generic.List”。
我意识到这些类型之间没有直接转换,但我不确定如何实现这一点。将来会有更多派生模板类和派生数据类,我将需要使用 GetDataSource 函数来获取数据项列表。
我想我想得太多了,但我已经在墙边呆了一段时间了,不确定我应该往哪个方向走。
List<T>
不是协变相关的T
, so List<Derived>
无法投射到List<Base>
.
Imagine List<T>
将是协变的。你可以写:
List<Base> bases = new List<Derived1>();
bases.Add(new Derived2());
Here Derived2
and Derived1
是不同的派生类。这是一个错误,所以List
不是协变相关的T
.
那么,你能做什么呢?
IEnumerable<T>
是协变的
var bases = new List<Base>(deriveds.AsEnumerable());
LINQ's Cast
var bases = deriveds.Cast<Base>()
.ToList();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)