C# 无法隐式转换类型System.Collections.Generic.List<;DerivedDataClass>;到System.Collections.Generic.List<;BaseDataClass>;
我需要一个抽象类,它包含一个方法来返回从基类或接口派生的项列表。我的代码如下:C# 无法隐式转换类型System.Collections.Generic.List<;DerivedDataClass>;到System.Collections.Generic.List<;BaseDataClass>;,c#,generics,inheritance,C#,Generics,Inheritance,我需要一个抽象类,它包含一个方法来返回从基类或接口派生的项列表。我的代码如下: public abstract class Template { //this should return the data to be used by the template public abstract List<BaseDataClass> GetDataSource(string sectionName); } 然后我有了继承抽象类的主派生模板类。在这里,我想返回Derive
public abstract class Template
{
//this should return the data to be used by the template
public abstract List<BaseDataClass> GetDataSource(string sectionName);
}
然后我有了继承抽象类的主派生模板类。在这里,我想返回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;
}
}
公共类派生模板:模板
{
公共覆盖列表GetDataSource(字符串sectionName)
{
列表数据=新列表();
//在列表中添加一些内容
返回数据;
}
}
当我尝试返回该列表时,我得到一个“无法隐式地将类型System.Collections.Generic.list转换为System.Collections.Generic.list”
我意识到这些类型之间没有直接转换,但我不确定如何才能实现这一点。将来会有更多的派生模板类和派生数据类,我需要使用GetDataSource函数来获取数据项列表。
我想我已经想得太多了,但我已经在一堵墙前呆了一段时间,不确定我应该朝哪个方向走 数据列表的类型必须是
list
而不是list
例如,这将编译:
List<BaseDataClass> data = new List<DerivedDataClass>().Select(x => (BaseDataClass)x).ToList();
List data=newlist();
您可以创建一个列表并添加如下项目:
List<BaseDataClass> data = new List<BaseDataClass>();
data.Add(new DerivedDataClass());
列表数据=新列表();
添加(新的DerivedDataClass());
列表
与T
无关,因此列表
不能强制转换为列表
想象一下,列表
是协变的。你可以写:
List base=newlist();
添加(新的Derived2());
这里的Derived2
和Derived1
是不同的派生类。这是一个错误,因此List
与T
不相关
那么,你能做什么
IEnumerable
是协变的
为什么需要将其强制转换回其基础,然后将其重新转换回派生类型?那有虐待的味道。向下投射(派生->基础)很好,但向上投射(基础->派生)通常不是您应该做的。这表明你不应该一开始就沮丧。我知道我想得太多了,谢谢!
List<BaseDataClass> data = new List<BaseDataClass>();
data.Add(new DerivedDataClass());
var bases = new List<Base>(deriveds.AsEnumerable());
var bases = deriveds.Cast<Base>()
.ToList();