C# 检查接口是否在编译时由类型实现
我有一个项目,我想保留对C# 检查接口是否在编译时由类型实现,c#,asp.net,.net,C#,Asp.net,.net,我有一个项目,我想保留对类型的引用,然后初始化该类型的实例。但是我需要一些编译时类型检查,所以我只能提供实现ITest接口的类型。我想我必须改变方法,但我不知道怎么做 private static Type currentType = null; public static void Initalize (Type current){ currentType = current; } public class Test : ITest{} public class Test2 {}
类型的引用,然后初始化该类型的实例。但是我需要一些编译时类型检查,所以我只能提供实现ITest
接口的类型。我想我必须改变方法,但我不知道怎么做
private static Type currentType = null;
public static void Initalize (Type current){
currentType = current;
}
public class Test : ITest{}
public class Test2 {}
应该可以通过typeof(Test)
但不能通过typeof(Test2)
为什么不使用泛型
private static Type currentType = null;
public static void Initalize <T>() where T: ITest {
currentType = typeof(T);
}
私有静态类型currentType=null;
公共静态void Initalize(),其中T:ITest{
currentType=typeof(T);
}
您需要将初始化方法更改为:
public static void Initialize(ITest current)
或者,您可以使用泛型来约束类型,例如
public static void Initialize<T>(T current) where T: ITest
publicstaticvoidinitialize(T current),其中T:ITest