我有一个表示接口的System.Type实例,我想获得该接口上所有属性的列表 - 包括从基接口继承的那些属性.我基本上希望从类获得的接口中获得相同的行为.
例如,给定此层次结构:
public interface IBase {
public string BaseProperty { get; }
}
public interface ISub : IBase {
public string SubProperty { get; }
}
public class Base : IBase {
public string BaseProperty { get { return "Base"; } }
}
public class Sub : Base, ISub {
public string SubProperty { get { return "Sub"; } }
}
Run Code Online (Sandbox Code Playgroud)
如果我在类上调用GetProperties typeof(Sub).GetProperties()- 那么我同时获得BaseProperty和SubProperty.我想对界面做同样的事情,但是当我尝试它时typeof(ISub).GetProperties()- 所有回来的都是SubProperty.
我尝试传递BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy给GetProperties,因为我对FlattenHierarchy的理解是它应该包含来自基类的成员,但行为完全相同.
我想我可以迭代Type.GetInterfaces()并在每个上调用GetProperties,但后来我依赖于接口上的GetProperties 永远不会返回基本属性(因为如果它曾经做过,我会得到重复).我宁愿不依赖于这种行为,至少看不到记录.
我怎么能:
各种各样的答案是在被发现标注到.NET Framework版本3.5上的特定MSDN页GetProperties(BindingFlags bindingFlags):
将BindingFlags.FlattenHierarchy传递给Type.GetXXX方法之一(例如Type.GetMembers),在查询接口类型本身时不会返回继承的接口成员.
[...]
要获取继承的成员,您需要查询其成员的每个已实现的接口.
示例代码也包括在内.这条评论是由微软发布的,所以我想你可以相信它.