简体   繁体   English

Java通用类类型的C#等效语法

[英]C# equivalent syntax for Java generic class type

I am looking for a equivalent syntax for java code below in C#. 我在下面的C#中寻找Java代码的等效语法。

ArrayList<Class <? extends A>> list = new ArrayList<Class<? extends A>>();
// Sample usage
list.add(A.class);
list.add(B.class); // B extends A

The list above basically only accept Sub Class of A (or A) as input. 上面的列表基本上只接受A(或A)的子类作为输入。

Thank in advance. 预先感谢。

There's no equivalent for that in C#. C#中没有等效的方法。 The generics in C# are quite different to those in Java in various ways, including the way covariance and contravariance work. C#中的泛型在各种方面都与Java中的泛型有很大不同,包括协方差和相反方差的工作方式。

You could have a generic method (or generic type) with a constraint on the type parameter like this: 您可能具有对类型参数施加约束的通用方法(或通用类型),如下所示:

public void Foo<T>(IList<T> list) where T : SomeClass

or 要么

public class Foo<T> where T : SomeClass

... but Type itself (the .NET equivalent of Class<T> ) is non-generic, so there's no way of saying "This is a list of types which extend A ". ...但是Type本身(相当于.NET的Class<T> )是非泛型的,因此无法说“这是扩展A的类型的列表”。

If you give us more information about what you're trying to achieve, we may be able to help you more. 如果您向我们提供有关您要实现的目标的更多信息,我们可能会为您提供更多帮助。

The C# language has generics from version 2.0 onwards: C#语言从2.0版开始具有泛型:

http://msdn.microsoft.com/en-us/library/512aeb7t.aspx http://msdn.microsoft.com/en-us/library/512aeb7t.aspx

Type constraints can be found here: 类型约束可以在这里找到:

http://msdn.microsoft.com/en-us/library/d5x73970.aspx http://msdn.microsoft.com/en-us/library/d5x73970.aspx

I'm mostly a Java programmer not a C# one so I'm not sure the exact syntax of what you need but you should be able to find it from there. 我主要是Java程序员,而不是C#程序员,所以我不确定您需要的确切语法,但是您应该可以从那里找到它。

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

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