[英]Check if a interface is implemented by a type in compile time
I have a project where I want to keep a reference to a Type
and later initalize instance of that type. 我有一个项目,我想保留对
Type
的引用,然后初始化该Type
实例。 But I want some compile-time type-checking so I only can provide types that implements the ITest
interface. 但是我需要一些编译时类型检查,因此我只能提供实现
ITest
接口的类型。 I think I have to change approach, but I can't see how. 我认为我必须改变方法,但是我看不出怎么做。
private static Type currentType = null;
public static void Initalize (Type current){
currentType = current;
}
public class Test : ITest{}
public class Test2 {}
It should be possible to pass in the typeof(Test)
but not typeof(Test2)
应该可以传入
typeof(Test)
但不能传入typeof(Test2)
Why dont you use generics? 为什么不使用泛型?
private static Type currentType = null;
public static void Initalize <T>() where T: ITest {
currentType = typeof(T);
}
You would need to change your Initialize
method to: 您需要将
Initialize
方法更改为:
public static void Initialize(ITest current)
Alternatively, you could use Generics to constrain the type eg 或者,您可以使用泛型来约束类型,例如
public static void Initialize<T>(T current) where T: ITest
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.