How do I determine if a property was overridden?

前提是你 提交于 2019-11-30 18:08:01

In order to ignore inherited members, you can use the BindingFlags.DeclaredOnly flag, which you're already doing.

But when properties are overridden, they are re-declared by the derived class. The trick is to then look at their accessor methods to determine if they are in fact overridden.

Type type = typeof(Foo);

foreach ( var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)) {
    var getMethod = property.GetGetMethod(false);
    if (getMethod.GetBaseDefinition() == getMethod) {
        Console.WriteLine(getMethod);
    }
}

If the property is overridden, its 'getter' MethodInfo will return a different MethodInfo from GetBaseDefinition.

None of these solutions worked well in my case. I ended up using DeclaringType to determine difference in definitions (I've provided the full function to give some context):

static public String GetExpandedInfo(Exception e)
{
    StringBuilder info = new StringBuilder();
    Type exceptionType = e.GetType();

    // only get properties declared in this type (i.e. not inherited from System.Exception)
    PropertyInfo[] propertyInfo = exceptionType.GetProperties(System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
    if (propertyInfo.Length > 0)
    {
        // add the exception class name at the top
        info.AppendFormat("[{0}]\n", exceptionType.Name);

        foreach (PropertyInfo prop in propertyInfo)
        {
            // check the property isn't overriding a System.Exception property (i.e. Message)
            // as that is a default property accessible via the generic Exception class handlers
            var getMethod = prop.GetGetMethod(false);
            if (getMethod.GetBaseDefinition().DeclaringType == getMethod.DeclaringType)
            {
                // add the property name and it's value
                info.AppendFormat("{0}: {1}\n", prop.Name, prop.GetValue(e, null));
            }
        }
    }

< WRONG > You can use property.DeclaringType to check which type declared the property. If it's different than the type you're currently reflecting on, it's overridden.< / WRONG >

It's been pointed out that an overriding type will redeclare the property. Didn't think of that. I guess you have to traverse the base types then to see if they declared a property with the same name. Then if it's declared in the reflected type AND by a base class it's overriden?

Oh Josh already pointed that out... :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!