假设以下假设的继承层次结构:
public interface IA
{
int ID { get; set; }
}
public interface IB : IA
{
string Name { get; set; }
}
使用反射并进行以下调用:
typeof(IB).GetProperties(BindingFlags.Public | BindingFlags.Instance)
只会产生接口的属性IB
,即“Name
".
如果我们对以下代码进行类似的测试,
public abstract class A
{
public int ID { get; set; }
}
public class B : A
{
public string Name { get; set; }
}
电话typeof(B).GetProperties(BindingFlags.Public | BindingFlags.Instance)
将返回一个数组PropertyInfo
对象为“ID
" and "Name
".
是否有一种简单的方法可以像第一个示例一样在接口的继承层次结构中查找所有属性?
我已将 @Marc Gravel 的示例代码调整为封装类和接口的有用扩展方法。它还首先添加了接口属性,我认为这是预期的行为。
public static PropertyInfo[] GetPublicProperties(this Type type)
{
if (type.IsInterface)
{
var propertyInfos = new List<PropertyInfo>();
var considered = new List<Type>();
var queue = new Queue<Type>();
considered.Add(type);
queue.Enqueue(type);
while (queue.Count > 0)
{
var subType = queue.Dequeue();
foreach (var subInterface in subType.GetInterfaces())
{
if (considered.Contains(subInterface)) continue;
considered.Add(subInterface);
queue.Enqueue(subInterface);
}
var typeProperties = subType.GetProperties(
BindingFlags.FlattenHierarchy
| BindingFlags.Public
| BindingFlags.Instance);
var newPropertyInfos = typeProperties
.Where(x => !propertyInfos.Contains(x));
propertyInfos.InsertRange(0, newPropertyInfos);
}
return propertyInfos.ToArray();
}
return type.GetProperties(BindingFlags.FlattenHierarchy
| BindingFlags.Public | BindingFlags.Instance);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)