Determine if Equals () is an override?

I have an instance of a type. How to determine if it overrides Equals ()?

+3
source share
2 answers
private static bool IsObjectEqualsMethod(MethodInfo m)
{
    return m.Name == "Equals"
        && m.GetBaseDefinition().DeclaringType.Equals(typeof(object));
}

public static bool OverridesEqualsMethod(this Type type)
{
    var equalsMethod = type.GetMethods()
                           .Single(IsObjectEqualsMethod);

    return !equalsMethod.DeclaringType.Equals(typeof(object));
}

Note that this indicates whether the object.Equalsinheritance hierarchy has been overridden anywhere type. To determine if an override is declared for the type itself, you can change the condition to

equalsMethod.DeclaringType.Equals(type)

EDIT: Clean up the method IsObjectEqualsMethod.

+6
source

If you list all methods of a type, use BindingFlags.DeclaredOnly, so you won’t see the methods that you just inherited but did not redefine.

0

Source: https://habr.com/ru/post/1762912/


All Articles