我需要一个抽象类,其中包含一个方法来返回从基类或接口(interface)派生的项目列表。我的代码如下:
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
不相关的协变体,所以List<Derived>
无法转换为 List<Base>
.
想象一下List<T>
将是协变的。你可以这样写:
List<Base> bases = new List<Derived1>();
bases.Add(new Derived2());
这里Derived2
和Derived1
是不同的派生类。这是一个错误,所以List
与 T
不存在协变关系.
那么,你能做什么?
IEnumerable<T>
是协变的
var bases = new List<Base>(deriveds.AsEnumerable());
LINQ 的 Cast
var bases = deriveds.Cast<Base>()
.ToList();
关于c# - 无法将类型 System.Collections.Generic.List<Derived DataClass> 隐式转换为 System.Collections.Generic.List<BaseD dataClass>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54593869/