C#,如何将派生列表 class 传递给接收基列表 class 的方法?

C#, How to pass a List of a Derived class to a method that receives a List of the Base class?

这是我的代码的简化版本:

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);

cannot convert from System.Collections.Generic.List<AppleBox> to System.Collections.Generic.List<FruitBox<Apple>>

我试过了:

AppleBox.ChooseFirst((List<FruitBox<Apple>>)appleBoxes);

但同样的错误。

我该如何继续?

您必须将派生 class 的引用保存到基础 class 变量中

List<FruitBox<Apple>> appleBoxes = new List<AppleBox>();

FruitBox<Apple> appleBox = new AppleBox();
appleBoxes.Add(appleBox);

appleBox.ChooseFirst(appleBoxes);

这种行为的原因在 C# 中已解释 here. In short - classes do not support varianceList<AppleBox> 不是 List<FruitBox<Apple>>

你能做什么:

  • “转换”集合(实际上是创建一个新集合):

OfType<>().ToList()

AppleBox.ChooseFirst(appleBoxes.OfType<FruitBox<Apple>>().ToList())

ToList

AppleBox.ChooseFirst(appleBoxes.ToList<FruitBox<Apple>>())
public abstract class FruitBox<T>
{
    public T item;

    public static T ChooseFirst(IEnumerable<FruitBox<T>> fruitBoxes)
    {
        return fruitBoxes.First().item;
    }
}