确保Type实例表示可从特定类分配的类型

mil*_*lin 8 c# java extends types

我主要是一个Java程序员,所以这将是"Java中与C#相同的东西是什么"的问题之一.因此,在Java中,您可以在编译时限制Class类型参数来扩展某个超类,如下所示:

public <T extends BaseClass> void foo(Class<T> type) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

乃至

public <T extends BaseClass> T foo(Class<T> type) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

您甚至可以链接多个接口:

public <T extends BaseClass & BaseInterface1 & BaseInterface2> void foo(Class<T> type) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

这是如何在C#中完成的?我知道你可以使用"where T:BaseClass",但这只适用于你有一个实例T.当你只有一个Type实例时呢?

编辑:

为了解释,这是我想要做的:

ASSEMBLY#1(base.dll):

abstract class BaseClass {
    abstract void Foo();
}
Run Code Online (Sandbox Code Playgroud)

ASSEMBLY#2(sub1.dll,引用base.dll):

class SubClass1 : BaseClass {
    void Foo() {
        // some code
    }
}
Run Code Online (Sandbox Code Playgroud)

ASSEMBLY#3(sub2.dll,引用base.dll):

class SubClass2 : BaseClass {
    void Foo() {
        // some other code
    }
}
Run Code Online (Sandbox Code Playgroud)

ASSEMBLY#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);
}
Run Code Online (Sandbox Code Playgroud)

所以,在这个例子中,我不关心'type'变量表示什么类,只要它是从BaseClass派生的,所以一旦我创建了一个实例,就可以调用Foo().

不是虚拟C#代码(而是一些Java模型)的部分是"通用"类型类:Type <T>和Type <?:BaseClass>.

InB*_*een 2

不,没有办法在编译时强制Type将 a 分配给泛型类型。如果我理解正确的话,你想要的是:

 void Foo<T>(Type type) { ... } //compile time error if an instace typed `type` is not assignable to `T`.
Run Code Online (Sandbox Code Playgroud)

意思是:

 void Foo<IFormattable>(typeof(string)); //ok
 void Foo<IDisposable>(typeof(string)); //compile time error
Run Code Online (Sandbox Code Playgroud)

显然,在运行时它很简单,但该语言在编译时不支持这一点。