如果检测的方法是使用反射覆盖(C#) [英] Detect if a method was overridden using Reflection (C#)

查看:184
本文介绍了如果检测的方法是使用反射覆盖(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.

推荐答案

由于类型测试1 ,就可以判断它是否有自己的<击>实施的声明 TESTME

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

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

如果声明从基类来了,这将评估假的。

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

请注意,由于这是测试的声明,而不是真正实现,这的将会的返回true,如果测试1 也是抽象的, TESTME 是抽象的,因为测试1 将有自己的声明。如果要排除这种情况下,添加&放大器;&安培; !实现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#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆