GetProperties() to return all properties for an interface inheritance hierarchy

前端 未结 6 765
北海茫月
北海茫月 2020-11-27 02:24

Assuming the following hypothetical inheritance hierarchy:

public interface IA
{
  int ID { get; set; }
}

public interface IB : IA
{
  string Name { get; se         


        
6条回答
  •  攒了一身酷
    2020-11-27 03:12

    Responding to @douglas and @user3524983, the following should answer the OP's question:

        static public IEnumerable GetPropertiesAndInterfaceProperties(this Type type, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Instance)
        {
            if (!type.IsInterface) {
                return type.GetProperties( bindingAttr);
            }
    
            return type.GetInterfaces().Union(new Type[] { type }).SelectMany(i => i.GetProperties(bindingAttr)).Distinct();
        }
    

    or, for an individual property:

        static public PropertyInfo GetPropertyOrInterfaceProperty(this Type type, string propertyName, BindingFlags bindingAttr = BindingFlags.Public|BindingFlags.Instance)
        {
            if (!type.IsInterface) {
                return type.GetProperty(propertyName, bindingAttr);
            }
    
            return type.GetInterfaces().Union(new Type[] { type }).Select(i => i.GetProperty( propertyName, bindingAttr)).Distinct().Where(propertyInfo => propertyInfo != null).Single();
        }
    

    OK next time I'll debug it before posting instead of after :-)

提交回复
热议问题