Determine if Equals() is an override?

橙三吉。 提交于 2019-12-01 09:24:26
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 reveals whether object.Equals has been overridden anywhere in the inheritance hierarchy of type. To determine if the override is declared on the type itself, you can change the condition to

equalsMethod.DeclaringType.Equals(type)

EDIT: Cleaned up the IsObjectEqualsMethod method.

If you enumerate all methods of a type use BindingFlags.DeclaredOnly so you won't see methods which you just inherited but not have overridden.

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