如何检查类型内的方法是否被重写?反射 C#

发布于 2024-12-22 19:51:49 字数 356 浏览 2 评论 0原文

可能的重复:
确定 Equals() 是否是覆盖?

我需要运行特定的部分特定类型是否覆盖Object.Equals的代码。

如何检查类型是否覆盖此方法?

在 VS 中输入 typeof(mytype).GetMethod("Equals"). 会带来一系列选项,但没有“IsOverriden”或类似的东西。

Possible Duplicate:
Determine if Equals() is an override?

I need to run specific pieces of code for whether a specific type overrides Object.Equals or not.

How can I check if a type overrides this method?

Typing typeof(mytype).GetMethod("Equals"). in VS brings me a wide list of options, but there's no "IsOverriden" or something like that.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

迟到的我 2024-12-29 19:51:49

检查DeclaringType是否为typeof(object)

Check whether DeclaringType is typeof(object).

稍尽春風 2024-12-29 19:51:49

有两种方法,首先,MethodInfo 类有一个 DeclaringType,您可以使用它来查看它是否是 System.Object。其次,您可以使用接受 BindingFlags 枚举并传入 DeclaredOnlyGetMethod 重载来确保您不会获取任何父对象。

There are two ways, first the MethodInfo class has a DeclaringType you can use to see if it is System.Object. Second you can use the overloads of GetMethod that accept a BindingFlags enum and pass in DeclaredOnly to ensure you don't get any parent objects.

顾忌 2024-12-29 19:51:49

您可以使用绑定标志来发挥自己的优势:

var t = typeof(mytype).GetMethod(
            "Equals",
            BindingFlags.Public |
            BindingFlags.Instance |
            BindingFlags.DeclaredOnly
        );

当且仅当 mytype 覆盖 Equals 时,t 才不是 null

You can use the binding flags to your advantage:

var t = typeof(mytype).GetMethod(
            "Equals",
            BindingFlags.Public |
            BindingFlags.Instance |
            BindingFlags.DeclaredOnly
        );

Then t is not null if and only if mytype overrides Equals.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文