c# - 无法将类型 System.Collections.Generic.List<Derived DataClass> 隐式转换为 System.Collections.Generic.List<BaseD dataClass>

标签 c# generics inheritance

我需要一个抽象类,其中包含一个方法来返回从基类或接口(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());

这里Derived2Derived1是不同的派生类。这是一个错误,所以ListT 不存在协变关系.

那么,你能做什么?

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/

相关文章:

c# - .NET 泛型 - 比较两个列表并过滤 : best practice

C# 如何使用类型为 "Type"的对象初始化泛型类

ruby-on-rails - 无效的单表继承类型:Rails

Python::父类(super class)中的属性在继承子类中不可用

c# - 获取包含表的数据库列表的有效方法

c# - 替换文本框的内部文本

c# - 我的 IEquatable 仍在为 Dictionary<T>[] 使用 Object.GetHashcode

c# - 在 ASP.NET 中序列化来自 RSS 提要的数据

java - 从 Java 泛型方法参数中排除枚举

java - 无法使用父类中的变量?