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

前端 未结 6 770
北海茫月
北海茫月 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:13

    I've tweaked @Marc Gravel's example code into a useful extension method encapsulates both classes and interfaces. It also add's the interface properties first which I believe is the expected behaviour.

    public static PropertyInfo[] GetPublicProperties(this Type type)
    {
        if (type.IsInterface)
        {
            var propertyInfos = new List();
    
            var considered = new List();
            var queue = new Queue();
            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);
    }
    

提交回复
热议问题