简体   繁体   English

如何在C#3.5中对泛型方法设置接口约束?

[英]How to put an interface constraint on a generic method in C# 3.5?

I want to achieve something like this in C# 3.5: 我希望在C#3.5中实现这样的目标:

public void Register<T>() : where T : interface {}

I can do it with class or struct, but how to do it with an interface? 我可以用类或结构来做,但是如何使用接口呢?

If you are asking about adding a constraint to a specific interface, that's straightforward: 如果您要求向特定接口添加约束,那么这很简单:

public void Register<T>( T data ) where T : ISomeInterface

If you are asking whether a keyword exists like class or struct to constrain the range of possible types for T, that is not available. 如果您询问某个关键字是否像类或结构一样存在,以限制T的可能类型范围,那么这是不可用的。

While you can write: 虽然你可以写:

public void Register<T>( T data ) where T : class // (or struct)

you cannot write: 你不能写:

public void Register<T>( T data ) where T : interface

C# and the CLR don't support overall interface constraints, although you can constrain it to a particular interface (see other answers). C#和CLR不支持整体接口约束,但您可以将其约束到特定接口(请参阅其他答案)。 The closest you can get is 'class' and check the type using reflection at runtime I'm afraid. 你可以得到的最接近的是'class'并且在运行时使用反射检查类型我害怕。 Why would you want an interface constraint in the first place? 为什么你首先想要一个接口约束?

您不能要求T是一个接口,因此您必须在运行时使用反射来断言。

If possible, I went with a solution like this. 如果可能的话,我选择了这样的解决方案。 It only works if you want several specific interfaces (eg those you have source access to) to be passed as a generic parameter, not any. 它只适用于您希望将几个特定接口(例如,您具有源访问权限的接口)作为通用参数传递,而不是任何接口。

  • I let my interfaces, which came into question, inherit an empty interface IInterface . 我让我的接口产生了问题,继承了一个空接口IInterface
  • I constrained the generic T parameter to be of IInterface 我将通用T参数约束为IInterface

In source, it looks like this: 在源代码中,它看起来像这样:

  • Any interface you want to be passed as the generic parameter: 您希望作为通用参数传递的任何接口:

     public interface IWhatever : IInterface { // IWhatever specific declarations } 
  • IInterface: IInterface:

     public interface IInterface { // Nothing in here, keep moving } 
  • The class on which you want to put the type constraint: 要放置类型约束的类:

     public class WorldPieceGenerator<T> where T : IInterface { // Actual world piece generating code } 

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

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