简体   繁体   English

如何将 Type 参数限制在某个接口上

[英]how to constraint the Type parameter to a certain interface only

Would it be possible to constraint a Type parameter to only allow caller to pass in class type that implements a certain interface?是否可以将 Type 参数限制为仅允许调用者传入实现某个接口的类类型? Take below as example:以下面为例:

public void RegisterProcessors(params Type[] types)

As it is now, caller can pass in any class type to this method.现在,调用者可以将任何类类型传递给此方法。 For example:例如:

RegisterProcessors(typeof(string));  

But what I really want is to only allow caller to pass in type that implements the IProcessor interface.但我真正想要的是只允许调用者传入实现 IProcessor 接口的类型。 Is that possible?那可能吗? Something like below, of course, below is syntactically wrong像下面这样的东西,当然,下面在语法上是错误的

public void RegisterProcessors(params Type<IProcessor>[] types)

No, basically.不,基本上。 If you were using generics, you could use如果您使用的是泛型,则可以使用

public void RegisterProcessor<T>() where T : IProcessor

But you can't combine that with params , so the caller would need to invoke it once per type.但是您不能将它与params结合使用,因此调用者需要对每种类型调用一次。 Which might be fine.这可能没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM