检测方法是否被覆盖

检测方法是否被覆盖

本文介绍了使用反射 (C#) 检测方法是否被覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个基类 TestBase,我在其中定义了一个虚拟方法 TestMe()

Say I have a base class TestBase where I define a virtual method TestMe()

class TestBase
{
    public virtual bool TestMe() {  }
}

现在我继承了这个类:

class Test1 : TestBase
{
    public override bool TestMe() {}
}

现在,使用反射,我需要查找 TestMe 方法是否已在子类中被覆盖 - 可能吗?

Now, using Reflection, I need to find if the method TestMe has been overriden in child class - is it possible?

我需要它做什么 - 我正在为对象"类型编写一个设计器可视化工具,以显示整个继承层次结构,并显示哪些虚拟方法在哪个级别被覆盖.

What I need it for - I am writing a designer visualizer for type "object" to show the whole hierarchy of inheritance and also show which virtual methods were overridden at which level.

推荐答案

给定类型Test1,可以判断它是否有自己的声明测试我:

Given the type Test1, you can determine whether it has its own declaration of TestMe:

typeof(Test1).GetMethod("TestMe").DeclaringType == typeof(Test1)

如果声明来自基类型,则计算结果为 false.

If the declaration came from a base type, this will evaluate false.

请注意,由于这是测试声明,而不是真正的实现,如果 Test1 也是抽象的并且 TestMe 是抽象的,则此返回真,因为 Test1 会有自己的声明.如果您想排除这种情况,请添加 &&!GetMethod("TestMe").IsAbstract

Note that since this is testing declaration, not true implementation, this will return true if Test1 is also abstract and TestMe is abstract, since Test1 would have its own declaration. If you want to exclude that case, add && !GetMethod("TestMe").IsAbstract

这篇关于使用反射 (C#) 检测方法是否被覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 04:22