Java C# 中的有界通配符

Java bounded wildcards in C#

我被这个问题困扰了几个小时。我正在尝试为 C# 找到等效的方法。

Java,作品:

public class Main
{
  public static void main(String[] args)
  {
    ArrayList<BaseList<? extends Base>> list = new ArrayList<>();
    list.add(new DerivedList());
  }
}

public class BaseList<T extends Base>
{

}

public class Base
{

}

public class DerivedList extends BaseList<Derived>
{

}

public class Derived extends Base
{

}

我需要 C# 中 ArrayList<BaseList<? extends Base>> 的等效方法。我希望有人帮助我。

在 C# 中是否可以通配您的变量?

C# 使用运行时类型具体化,而 Java 使用类型擦除。这意味着在 Java 中,ArrayList<Foo> 在运行时与 ArrayList<Bar> 相同 class。 不是 C# 中的情况,因此您不能像那样丢弃类型参数。

您可以尝试像这样解决这个问题:

public abstract class BaseList
{
}

public class BaseList<T> : BaseList
    where T : Base
{
}

然后使用List<BaseList>

您无法完全按照您的描述进行操作,但有一些解决方法。一个在另一个答案中提到,另一个是使用接口代替:

public class Main
{
    public static void main(String[] args)
    {
        var list = new List<IBaseList<Base>>();
        list.Add(new DerivedList());
    }
}
// note "out" here
public interface IBaseList<out T> where T : Base {

}

public class BaseList<T> : IBaseList<T> where T : Base {

}

public class Base {

}

public class DerivedList : IBaseList<Derived> {

}

public class Derived : Base {

}