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

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

    This seems a bit painful for no apparent reason!

    My solution is for the case where you know the name of the property you are looking for and is pretty simple.

    I have a class for making reflection a bit easier that I just had to add this case to:

    public class PropertyInfoWrapper
    {
        private readonly object _parent;
        private readonly PropertyInfo _property;
    
        public PropertyInfoWrapper(object parent, string propertyToChange)
        {
            var type = parent.GetType();
            var privateProperties= type.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
    
            var property = type.GetProperty(propertyToChange) ??
                           privateProperties.FirstOrDefault(p => UnQualifiedNameFor(p) == propertyName);
    
            if (property == null)
                throw new Exception(string.Format("cant find property |{0}|", propertyToChange));
    
            _parent = parent;
            _property = property;
        }
    
        private static string UnQualifiedNameFor(PropertyInfo p)
        {
            return p.Name.Split('.').Last();
        }
    
        public object Value
        {
            get { return _property.GetValue(_parent, null); }
            set { _property.SetValue(_parent, value, null); }
        }
    }
    

    You cant just do == on name because explicitly implemented properties have fully qualified names.

    GetProperties needs both the search flags to get at private properties.

提交回复
热议问题