[英]C#, How to pass a List of a Derived class to a method that receives a List of the Base class?
This is a simplified version of my code:这是我的代码的简化版本:
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
}
}
I have an error in the line:我在该行中有一个错误:
AppleBox.ChooseFirst(appleBoxes);
cannot convert from
System.Collections.Generic.List<AppleBox>
toSystem.Collections.Generic.List<FruitBox<Apple>>
无法从System.Collections.Generic.List<AppleBox>
转换为System.Collections.Generic.List<FruitBox<Apple>>
I tried:我试过了:
AppleBox.ChooseFirst((List<FruitBox<Apple>>)appleBoxes);
But same error.但是同样的错误。
How do I have to proceed?我该如何进行?
The reason for such behaviour is explained here .这种行为的原因在这里解释。 In short - classes do not support variance in C# and List<AppleBox>
is not List<FruitBox<Apple>>
.简而言之 - 类不支持C#中的差异并且List<AppleBox>
不是List<FruitBox<Apple>>
。
What you can do:你可以做什么:
with OfType<>().ToList()
使用OfType<>().ToList()
AppleBox.ChooseFirst(appleBoxes.OfType<FruitBox<Apple>>().ToList())
or just ToList
或者只是ToList
AppleBox.ChooseFirst(appleBoxes.ToList<FruitBox<Apple>>())
ChooseFirst
signature to work with covariant IEnumerable<out T>
interface:更改ChooseFirst
签名以使用协变IEnumerable<out T>
接口:public abstract class FruitBox<T>
{
public T item;
public static T ChooseFirst(IEnumerable<FruitBox<T>> fruitBoxes)
{
return fruitBoxes.First().item;
}
}
You will have to hold the reference of the derived class into the base class variable您必须将派生 class 的引用保存到基础 class 变量中
List<FruitBox<Apple>> appleBoxes = new List<AppleBox>();
FruitBox<Apple> appleBox = new AppleBox();
appleBoxes.Add(appleBox);
appleBox.ChooseFirst(appleBoxes);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.