sách gpt4 ăn đã đi

c# - 无法将类型 System.Collections.Generic.List 隐式转换为 System.Collections.Generic.List

In lại Tác giả: Walker 123 更新时间:2023-11-30 21:30:13 24 4
mua khóa gpt4 giày nike

我需要一个抽象类,其中包含一个方法来返回从基类或接口(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 函数来获取数据项列表。 我想我想得太多了,但我已经在墙边呆了一段时间了,不确定我应该朝哪个方向走。

câu trả lời hay nhất

ListT 不相关的协变体,所以List无法转换为 List .

想象一下List将是协变的。你可以这样写:

List bases = new List();
bases.Add(new Derived2());

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

那么,你能做什么?

IEnumerable是协变的

var bases = new List(deriveds.AsEnumerable());

LINQ 的 Cast

var bases = deriveds.Cast()
.ToList();

关于c# - 无法将类型 System.Collections.Generic.List 隐式转换为 System.Collections.Generic.List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54593869/

24 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress