简体   繁体   中英

C#'s equivalent of Java's <? extends Base> in generics

In Java, I can do the following: (assume Subclass extends Base ):

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

What is the equivalent in C# .NET? There is no ? extends ? extends keyword apparently and this does not work:

List<Base> aList = 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.

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

没有完全等效(因为类型系统不完全一样的方式工作,与类型擦除和所有),但你可以得到非常类似的功能inout使用协方差和逆变

如果您正在寻找两种类型的泛型,请看一下:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM