【问题标题】:Force generic interface implementation in C#在 C# 中强制实现泛型接口
【发布时间】:2010-08-30 13:19:56
【问题描述】:

无论如何强制一个泛型定义的约束来实现一个“泛型接口”......也就是说,我希望该类支持传递一个接口和一个约束它的泛型类,以便该类实现该接口。例如,如果我说:

MyGenericClass<IMyInterface, MyImplementation>.DoSomething();

这应该受到约束,以便 MyImplementation 实现 IMyInterface

据我所知可以通过

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

现在,还有没有强制 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);}

并将列表仅限于接口(因为它应该返回某些接口的实现)

【问题讨论】:

    标签: c# generics interface constraints


    【解决方案1】:

    你的意思是,可以像where T : interface一样对T施加约束吗?

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

    我相信,你所拥有的已经是最接近的了。

    出于好奇,您希望将T 限制为接口的原因是什么?

    或者你的意思是可以在T 上为T 设置约束以实现一些特定接口?

    如果是,那么:只需有两个where 子句(例如where S : T where T : U)。

    【讨论】:

    • 哦,我本来打算这样做的:public static List interfacelist = new List;公共静态无效添加(S输入);是的,如果 T 只是一个基类,它也可以工作,但客户端应该获取接口,而不是基类。
    【解决方案2】:
    where T: IMyOtherInterfaceForT
    

    例子:

        public class Test<T, V>
        where T : V
        where V : IEnumerable<int>
        {
        }
    

    【讨论】:

      【解决方案3】:

      你可以做这样的事情来在运行时而不是编译时强制它。

      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" );
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 2020-05-14
        • 1970-01-01
        • 2020-04-03
        • 1970-01-01
        • 2010-11-14
        相关资源
        最近更新 更多