在泛型中,C # 等效于 Java 的 < ? 扩展 Base >

在 Java 中,我可以执行以下操作: (假设 Subclass扩展了 Base) :

ArrayList<? extends Base> aList = new ArrayList<Subclass>();

什么是 C # . NET 中的等价物? 显然没有 ? extends关键字,而且这也不起作用:

List<Base> aList = new List<Subclass>();
59673 次浏览

There is no exact equivalent (since the type system doesn't work in quite the same way, with type erasure and all), but you can get very similar functionality with in and out using covariance and contravariance.

Look into Covariance and Contravariance introduced with .Net 4.0. But it only works with interfaces right now.

Example:

IEnumerable<Base> list = new List<SubClass>();

Actually there is an Equivalent(sort of), the where keyword. I don't know how "close" it is. I had a function I needed to do something similar for.

I found an msdn page about it.

I don't know if you can do this inline for a variable, but for a class you can do:
public class MyArray<T> where T: someBaseClass
or for a function
public T getArrayList<T>(ArrayList<T> arr) where T: someBaseClass

I didn't see it on the page but using the where keyword it might be possible for a variable.

If you are looking for two type generics, Take a look at this:

    void putAll<K1, V1>(Dictionary<K1,V1> map) where K1 : K where V1 : V;