代码之家  ›  专栏  ›  技术社区  ›  Jorge Córdoba

用C语言强制实现通用接口#

  •  8
  • Jorge Córdoba  · 技术社区  · 15 年前

    不管怎样,是否有强制泛型定义的约束来实现“泛型接口”。。。也就是说,我希望类支持传递接口和约束接口的泛型类,以便类实现接口。例如,如果我说:

    MyGenericClass<IMyInterface, MyImplementation>.DoSomething();
    

    据我所知

    public class Dynamic_Loader<T, S> where S: T
    

    编辑: 这样做的目的是:

    private static List<T> interfaceList = new List<T>();
    
    public static List<T> InterfaceList {get { return interfaceList;}}
    
    public static void Add(S input) { interfaceList.Add(input);}
    

    3 回复  |  直到 15 年前
        1
  •  8
  •   Dan Tao    15 年前

    你的意思是,约束也能被施加吗 T 喜欢 where T : interface

    如果是,那么 this list 几乎涵盖了你的选择。

    我相信,你所拥有的一切都是近在咫尺。

    出于好奇,你想约束自己的理由是什么 作为一个接口?

    或者你的意思是约束也可以被施加 T型 对于 实施 一些 具体的

    如果是,那么 where 条款(例如。, where S : T where T : U ).

        2
  •  3
  •   Tokk    15 年前
    where T: IMyOtherInterfaceForT
    

        public class Test<T, V>
        where T : V
        where V : IEnumerable<int>
        {
        }
    
        3
  •  2
  •   ScottS    12 年前

    您可以这样做,在运行时而不是编译时强制执行它。

    public class Test<T> where T : class
    {
      public Test()
      {
        Type t = typeof( T );
        if( !t.IsInterface )
          throw new ArgumentException( "T must be an interface type" );
      }
    }