我主要是一名 Java 程序员,所以这将是“Java 中的这个东西与 C# 中的东西是什么”这样的问题之一。因此,在 Java 中,您可以在编译时限制类类型参数以扩展某个父类(super class),如下所示:
public <T extends BaseClass> void foo(Class<T> type) {
...
}
甚至
public <T extends BaseClass> T foo(Class<T> type) {
...
}
您甚至可以链接多个接口(interface):
public <T extends BaseClass & BaseInterface1 & BaseInterface2> void foo(Class<T> type) {
...
}
这是如何在 C# 中完成的?我知道您可以使用“where T : BaseClass”,但这仅适用于您拥有实例 T 的情况。如果您只有一个 Type 实例呢?
编辑:
为了解释,这是我想做的:
程序集 #1(base.dll):
abstract class BaseClass {
abstract void Foo();
}
ASSEMBLY #2(sub1.dll,引用 base.dll):
class SubClass1 : BaseClass {
void Foo() {
// some code
}
}
汇编 #3(sub2.dll,引用 base.dll):
class SubClass2 : BaseClass {
void Foo() {
// some other code
}
}
汇编 #4(main.dll,引用 base.dll):
class BaseClassUtil {
static void CallFoo(Type<T> type) where T : BaseClass {
T instance = (T)Activator.CreateInstance(type);
instance.Foo();
}
}
public static void Main(String[] args) {
// Here I use 'args' to get a class type,
// possibly loading it dynamically from a DLL
Type<? : BaseClass> type = LoadFromDll(args); // Loaded from DLL
BaseClassUtil.CallFoo(type);
}
所以,在这个例子中,我不关心“type”变量代表什么类,只要它是从 BaseClass 派生的,所以一旦我创建了一个实例,就可以调用 Foo()。
不是有效 C# 代码的部分(而是一些 Java 模型)是“通用”类型类:Type
最佳答案
不,没有办法在编译时强制将 Type
分配给通用类型。如果我没理解错的话,你想要的是:
void Foo<T>(Type type) { ... } //compile time error if an instace typed `type` is not assignable to `T`.
这意味着:
void Foo<IFormattable>(typeof(string)); //ok
void Foo<IDisposable>(typeof(string)); //compile time error
显然在运行时它是微不足道的,但该语言在编译时不支持它。
关于java - 确保 Type 实例代表可从某个类分配的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41101506/