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

后端 未结 9 1018
[愿得一人]
[愿得一人] 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:44

    Jacob's code is missing a filter:

            var props = typeof(TempClass).GetInterfaces().Where(i => i.Name=="TempInterface").SelectMany(i => i.GetProperties());
            foreach (var prop in props)
                Console.WriteLine(prop);
    
    0 讨论(0)
  • 2021-01-03 20:52

    A simple helper class that could help:

    public class InterfacesPropertiesMap
    {
        private readonly Dictionary<Type, PropertyInfo[]> map;
    
        public InterfacesPropertiesMap(Type type)
        {
            this.Interfaces = type.GetInterfaces();
            var properties = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
    
            this.map = new Dictionary<Type, PropertyInfo[]>(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.

    0 讨论(0)
  • 2021-01-03 20:53

    I think the class you are looking for is System.Reflection.InterfaceMapping.

    Type ifaceType = typeof(TempInterface);
    Type tempType = typeof(TempClass);
    InterfaceMapping map = tempType.GetInterfaceMap(ifaceType);
    for (int i = 0; i < map.InterfaceMethods.Length; i++)
    {
        MethodInfo ifaceMethod = map.InterfaceMethods[i];
        MethodInfo targetMethod = map.TargetMethods[i];
        Debug.WriteLine(String.Format("{0} maps to {1}", ifaceMethod, targetMethod));
    }
    
    0 讨论(0)
提交回复
热议问题