C# 相当于 Java 的 <?扩展基础>在泛型中 [英] C#'s equivalent of Java's <? extends Base> in generics
问题描述
在 Java 中,我可以执行以下操作:(假设 Subclass
extends Base
):
In Java, I can do the following: (assume Subclass
extends Base
):
ArrayList<? extends Base> aList = new ArrayList<Subclass>();
C# .NET 中的等价物是什么?没有<代码>?extends 关键字显然是行不通的:
What is the equivalent in C# .NET? There is no ? extends
keyword apparently and this does not work:
List<Base> aList = new List<Subclass>();
推荐答案
实际上有一个 Equivalent(sort of),where
关键字.我不知道它有多接近".我有一个函数需要做类似的事情.
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.
我找到了一个 msdn 页面 关于它.
I found an msdn page about it.
我不知道你是否可以对一个变量进行内联,但对于一个类你可以这样做:公共类 MyArray
或用于函数public T getArrayList
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
我没有在页面上看到它,但使用 where
关键字可能是一个变量.
I didn't see it on the page but using the where
keyword it might be possible for a variable.
这篇关于C# 相当于 Java 的 <?扩展基础>在泛型中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!