How do I use reflection to get properties explicitly implementing an interface?

后端 未结 9 1123
[愿得一人]
[愿得一人] 2021-01-03 20:18

More specifically, if I have:

public class TempClass : TempInterface
{

    int TempInterface.TempProperty
    {
        get;
        set;
    }
    int Temp         


        
9条回答
  •  清歌不尽
    2021-01-03 20:52

    A simple helper class that could help:

    public class InterfacesPropertiesMap
    {
        private readonly Dictionary map;
    
        public InterfacesPropertiesMap(Type type)
        {
            this.Interfaces = type.GetInterfaces();
            var properties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
    
            this.map = new Dictionary(this.Interfaces.Length);
    
            foreach (var intr in this.Interfaces)
            {
                var interfaceMap = type.GetInterfaceMap(intr);
                this.map.Add(intr, properties.Where(p => interfaceMap.TargetMethods
                                                        .Any(t => t == p.GetGetMethod(true) ||
                                                                  t == p.GetSetMethod(true)))
                                             .Distinct().ToArray());
            }
        }
    
        public Type[] Interfaces { get; private set; }
    
        public PropertyInfo[] this[Type interfaceType]
        {
            get { return this.map[interfaceType]; }
        }
    }
    

    You'll get properties for each interface, even explicitly implemented.

提交回复
热议问题