简体   繁体   English

在编译时检查接口是否由类型实现

[英]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.

相关问题 编译时间类型检查 - Compile time type check 在编译时按类型推断接口 - Infer interface by type at compile time 没有实现的接口没有编译错误 - No compile error for a not implemented interface 具有协方差/协方差的已实现接口会生成编译时错误 - Implemented interface with co/contravariance generates compile time error 为什么foreach跳过对接口类型的编译时类型检查? - Why does foreach skip compile time type checking on interface types? 在不知道编译时的类型的情况下解析Windsor的通用接口? - Resolve generic interface with Windsor without knowing the type at compile time? 具有接口列表的接口,如何选择由接口实现的一种类型 - Interface with a list of interface, how to choose one type implemented by interface 是否可以进行编译时检查,以确保将类型标记为Serializable属性 - Is it possible to have a compile time check that a type is marked with the Serializable attribute 编译时检查带有接口的字典条目类型的正确性 - compile-time check of correctness of dictionary entry type with interfaces C#函数返回类型的已实现接口 - C# function to return the implemented interface of a type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM