简体   繁体   English

C#相当于Java的?在泛型中扩展Base>

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

In Java, I can do the following: (assume Subclass extends Base ): 在Java中,我可以执行以下操作:(假设Subclass扩展Base ):

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

What is the equivalent in C# .NET? C#.NET中的等价物是什么? There is no ? extends 没有? extends ? extends keyword apparently and this does not work: 显然? extends关键字,这不起作用:

List<Base> aList = new List<Subclass>();

Actually there is an Equivalent(sort of), the where keyword. 实际上有一个Equivalent(有点), where关键字。 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. 我找到了一个关于它的msdn页面

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. 我没有在页面上看到它,但使用where关键字可能是变量。

Look into Covariance and Contravariance introduced with .Net 4.0 . 研究.Net 4.0引入的CovarianceContravariance But it only works with interfaces right now. 但它现在只适用于interfaces

Example: 例:

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

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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