C#,如何将派生类的列表传递给接收基类列表的方法?
这是我的代码的简化版本:
using System.Collections.Generic;
public abstract class FruitBox<T>
{
public T item;
public static T ChooseFirst(List<FruitBox<T>> fruitBoxes)
{
return fruitBoxes[0].item;
}
}
public class Apple
{
}
public class AppleBox : FruitBox<Apple>
{
}
public class FruitShop
{
List<AppleBox> appleBoxes = new List<AppleBox>();
public void Main()
{
AppleBox appleBox = new AppleBox();
appleBoxes.Add(appleBox);
AppleBox.ChooseFirst(appleBoxes); // => Error here
}
}
我的行中有一个错误:
AppleBox.ChooseFirst(appleBoxes);
无法从
System.Collections.Generic.List
转换为System.Collections.Generic.List
>
我尝试过:
AppleBox.ChooseFirst((List<FruitBox<Apple>>)appleBoxes);
但同样的错误。
我该如何继续?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此处解释了这种行为的原因。简而言之 - 类不支持 variance< C# 中的 /a> 和
List
不是List>
。你可以做什么:
使用
OfType<>().ToList()
或只是
ToList
ChooseFirst
签名与协变一起使用IEnumerable
接口:The reason for such behaviour is explained here. In short - classes do not support variance in C# and
List<AppleBox>
is notList<FruitBox<Apple>>
.What you can do:
with
OfType<>().ToList()
or just
ToList
ChooseFirst
signature to work with covariantIEnumerable<out T>
interface:您必须将派生类的引用保存到基类变量中
You will have to hold the reference of the derived class into the base class variable