代码之家  ›  专栏  ›  技术社区  ›  andrecarlucci

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

  •  5
  • andrecarlucci  · 技术社区  · 15 年前

    我想在C 3.5中实现类似的目标:

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

    我可以用类或结构来做,但是如何用接口来做呢?

    4 回复  |  直到 15 年前
        1
  •  4
  •   thecoop    15 年前

    C和clr不支持整体接口约束,尽管您可以将其约束到特定接口(参见其他答案)。最接近的是“类”,在运行时使用反射检查类型。为什么首先需要一个接口约束?

        2
  •  6
  •   LBushkin    15 年前

    如果您要向特定接口添加约束,这很简单:

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

    如果您询问关键字是否存在,例如类或结构,以约束T的可能类型的范围,那么这是不可用的。

    你可以写:

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

    你不能写:

    public void Register<T>( T data ) where T : interface
    
        3
  •  0
  •   Matt Howells    15 年前

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

        4
  •  0
  •   Ray Brian Agnew    10 年前

    如果可能的话,我提出了这样的解决方案。只有当您希望将多个特定接口(例如那些您有源代码访问权的接口)作为通用参数(而不是任何接口)传递时,它才起作用。

    • 我让出现问题的接口继承一个空接口 IInterface .
    • 我将一般t参数约束为 I接口

    在source中,它看起来如下:

    • 要作为泛型参数传递的任何接口:

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

      public interface IInterface
      {
          // Nothing in here, keep moving
      }
      
    • 要在其上放置类型约束的类:

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