.NET - 获取通用接口的所有实现?
关于“通过反射实现接口”的答案显示了如何获取一个接口的所有实现界面。但是,给定一个通用接口 IInterface
,以下内容不起作用:
var types = TypesImplementingInterface(typeof(IInterface<>))
任何人都可以解释如何修改该方法吗?
An answer on " Implementations of interface through Reflection " shows how to get all implementations of an interface. However, given a generic interface, IInterface<T>
, the following doesn't work:
var types = TypesImplementingInterface(typeof(IInterface<>))
Can anyone explain how I can modify that method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用这样的东西:
虽然它可以抛出
TypeLoadException
但这是原始代码中已经存在的问题。例如,在 LINQPad 中它不起作用,因为某些库无法加载。You can use something like this:
It can throw a
TypeLoadException
though but that's a problem already present in the original code. For example in LINQPad it doesn't work because some libraries can't be loaded.它不起作用,因为
IInterface
It doesn't work because
IInterface<object>
(usingSystem.Object
for T as an example) doesn't inherit from the "open" generic typeIInterface<>
. A "closed" generic type is a root type, just likeIFoo
. You can only search for closed generic types, not open ones, meaning you could find everything that inherits fromIInterface<int>
.IFoo
does not have a base class, nor doesIInterface<object>
orIInterface<string>
etc.