我是一个.NET人,所以让我首先断言我对一些Java概念的理解 - 如果我错了,请纠正我.
Java Generics支持有界通配符的概念:
class GenericClass< ? extends IInterface> { ... }
Run Code Online (Sandbox Code Playgroud)
...类似于.NET where限制:
class GenericClass<T> where T: IInterface { ... }
Run Code Online (Sandbox Code Playgroud)
Java的Class类描述了一个类型,并且大致相当于.NET Type类
到现在为止还挺好.但是我找不到足够接近Java的通用类型Class<T>,其中T是有界通配符.这基本上对所Class代表的类型施加了限制.
让我举一个Java的例子.
String custSortclassName = GetClassName(); //only known at runtime,
// e.g. it can come from a config file
Class<? extends IExternalSort> customClass
= Class.forName("MyExternalSort")
.asSubclass(IExternalSort.class); //this checks for correctness
IExternalSort impl = customClass.newInstance(); //look ma', no casting!
Run Code Online (Sandbox Code Playgroud)
我在.NET中最接近的是这样的:
String custSortclassName = GetClassName(); …Run Code Online (Sandbox Code Playgroud) 我试图将一些使用(有界)通配符泛型的Java代码转换为C#.我的问题是,Java似乎允许泛型类型在与通配符一起使用时既是协变的又是逆变的.
[这是关于一个更简单的有界通配符案例的前一个问题的衍生物]
Java - 作品:
class Impl { }
interface IGeneric1<T extends Impl> {
void method1(IGeneric2<?> val);
T method1WithParam(T val);
}
interface IGeneric2<T extends Impl> {
void method2(IGeneric1<?> val);
}
abstract class Generic2<T extends Impl> implements IGeneric2<T> {
// !! field using wildcard
protected IGeneric1<?> elem;
public void method2(IGeneric1<?> val1) {
val1.method1(this);
//assignment from wildcard to wildcard
elem = val1;
}
}
abstract class Generic<T extends Impl> implements IGeneric1<T>, IGeneric2<T> {
public void method1(IGeneric2<?> val2) {
val2.method2(this);
} …Run Code Online (Sandbox Code Playgroud)