强制通用接口实现在C# [英] Force generic interface implementation in C#
问题描述
有没有反对强制一个通用定义的约束实现一个通用接口...也就是说,我想类支持传递一个接口和一个类约束它,使类实现接口。例如,如果我说:
Is there anyway to force a constraints for a generic definition to implement a "generic interface" ... that is, I want the class to support passing an interface and a generic class constraining it so that the class implements the interface. For example if I say:
MyGenericClass<IMyInterface, MyImplementation>.DoSomething();
这应该限制使MyImplementation实现IMyInterface
That should be constrained so that MyImplementation implements IMyInterface
据我所知,可以通过
public class Dynamic_Loader<T, S> where S: T
现在,有没有还强制T是一个接口?
Now, is there anyway to also force T to be an interface?
修改:这样做的目的是:
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);}
并且列表仅限于接口(因为它应该返回某些接口的实现)
and have the list restricted to only interfaces (since it is supposed to return implementations of certain interfaces)
推荐答案
你也可以在 T
c $ c>?
Do you mean, can a constraint also be put on T
like where T : interface
?
如果是这样,则否:这份清单几乎涵盖您的选项。
If so, then no: this list pretty much covers your options.
我相信。
出于好奇,你想要约束 T
是一个接口?
Out of curiosity, what would be your reason for wanting to constrain T
to be an interface?
或者你的意思是可以在 T
T
到实现某些特定界面?
Or do you mean can a constraint also be put on T
for T
to implement some specific interface?
如果是这样,则是:只需要两个其中
子句(例如,其中S:T其中T: U
)。
If so, then yes: simply have two where
clauses (e.g., where S : T where T : U
).
这篇关于强制通用接口实现在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!