相关疑难解决方法(0)

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

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

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)

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

c# generics interface constraints

8
推荐指数
1
解决办法
4269
查看次数

标签 统计

c# ×1

constraints ×1

generics ×1

interface ×1