c#中的Java有界通配符

本文关键字:通配符 Java 中的 | 更新日期: 2023-09-27 18:18:04

我被这个问题困了好几个小时。我正在尝试为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有界通配符

您不能完全按照您所描述的那样做,但是有一些变通方法。一个是在另一个答案中提到的,另一个是使用interface:

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 {
}

c#使用运行时类型具体化,而Java使用类型擦除。这意味着在Java中,ArrayList<Foo>在运行时与ArrayList<Bar>是同一个类。这是而不是c#中的,所以你不能像那样丢掉类型参数。

你可以试着这样做:

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

然后使用List<BaseList>