如何使用反射来判断一个类是否本地实现了某个接口?
问题是 Type.GetInterfaces() 返回类实现的所有接口,这包括由继承的基类定义/实现的任何接口。当我试图找出类本地引用/实现的接口(因此排除基类中引用/定义的任何接口)时,我遇到了问题。
我想做一些类似于 type.GetProperties() 的事情,它可以采用 BindingFlags,因此以下代码将获取在被引用的类型内声明的所有公共/私有属性(并且排除在基类中声明的所有属性)。
type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
我已尝试以下操作,但由于“.DeclaringType”始终为空而失败。
foreach (var implementedInterface in type.GetInterfaces())
{
if (implementedInterface.DeclaringType == type)
{
locallyDefinedInterfaces.Add(implementedInterface);
}
}
The problem is that Type.GetInterfaces() returns all interfaces that a class implements, this includes any interfaces that are defined/implemented by inherited base classes. I'm running into problems when I'm trying to find out just the interfaces that a class locally references / implements (so excluding any interfaces referenced/defined within a base class).
I want to do something similar to type.GetProperties() which can take BindingFlags, so the following code will get all public/private properties that are declared inside the type being referenced (and all properties declared in base classes are excluded).
type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
I've tried the following, but it fails as ".DeclaringType" is always null.
foreach (var implementedInterface in type.GetInterfaces())
{
if (implementedInterface.DeclaringType == type)
{
locallyDefinedInterfaces.Add(implementedInterface);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能用集合定义的所有接口来填充集合吗?然后,对于从目标类派生的类开始的每个类,获取该类实现的所有接口,并从列表中删除。重复并冲洗,直到不再有基类。列表中剩下的都是由原始类单独实现的接口。
注意:可能有更好的方法来做到这一点,这只是一个建议。
Can you not populate a collection with all interfaces it defines. Then, for each class starting from the one your target class derives from, get all interfaces that that class implements, removing from your list as you go. Repeat-and-rinse until you have no more base-classes. Whatever remains in your list are interfaces solely implemented by your original class.
Note: There may well be better ways of doing this, this is just a suggestion.
请看这里:
http://www.clariusconsulting.net/ blogs/kzu/archive/2010/12/03/Howtoinspectatypeinheritancetreeproperly.aspx
这是才华横溢的 Daniel Cazzulino 的帖子。
Look here:
http://www.clariusconsulting.net/blogs/kzu/archive/2010/12/03/Howtoinspectatypeinheritancetreeproperly.aspx
This is a post by brilliant Daniel Cazzulino.
声明类型为 null 的原因可能是因为它是 null...(因为接口未在任何类型中声明)。只是一个见解
The reason that declared type is null, is probably because it is null... (since the interface is not declared within any type). Just an insight
如何使用
is
运算符来检查该类是否属于该类型。例如
How about to use the
is
operator to check if the class is of that type.e.g