在C#中强制通用接口实现

时间:2010-08-30 13:19:56

标签: c# generics interface constraints

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

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

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

3 个答案:

答案 0 :(得分:7)

您的意思是,约束是否也可以T where T : interface加上约会?

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

我相信,你所拥有的一切尽可能接近。

出于好奇,您希望约束T成为界面的原因是什么?

或者您是否也可以TT 实施某些特定的接口提供约束?

如果是,那么:只有两个where条款(例如where S : T where T : U)。

答案 1 :(得分:3)

where T: IMyOtherInterfaceForT

示例:

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

答案 2 :(得分:2)

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

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