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

Jor*_*oba 8 c# generics interface constraints

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

MyGenericClass<IMyInterface, MyImplementation>.DoSomething();
Run Code Online (Sandbox Code Playgroud)

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

据我所知,可以通过实现

public class Dynamic_Loader<T, S> where S: T
Run Code Online (Sandbox Code Playgroud)

现在,无论如何也迫使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);}
Run Code Online (Sandbox Code Playgroud)

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

Dan*_*Tao 7

你的意思是,可以约束也被提上Twhere T : interface

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

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

出于好奇,你想要约束T成为一个界面的原因是什么?

还是你的意思可以约束也提上TT实现一些特定的接口?

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