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

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

MyGenericClass.DoSomething(); 

这应该受到限制,以便MyImplementation实现IMyInterface

据我所知,可以通过实现

 public class Dynamic_Loader where S: T 

现在,无论如何也迫使T成为一个界面?

编辑:这样做的目的是:

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

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

你的意思是,一个约束也可以放在T就像where T : interface

如果是,那么 : 这个列表几乎涵盖了您的选择。

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

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

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

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

 where T: IMyOtherInterfaceForT 

例:

  public class Test where T : V where V : IEnumerable { } 

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

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