简体   繁体   中英

C# equivalent syntax for Java generic class type

I am looking for a equivalent syntax for java code below in C#.

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.

Thank in advance.

There's no equivalent for that in C#. The generics in C# are quite different to those in Java in various ways, including the way covariance and contravariance work.

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 ".

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:

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

Type constraints can be found here:

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.

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