使用反射调用覆盖的基本方法 [英] Use reflection to invoke an overridden base method

查看:24
本文介绍了使用反射调用覆盖的基本方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用反射调用被派生类覆盖的基方法?

How to use reflection call a base method that is overridden by derived class?

class Base
{
    public virtual void Foo() { Console.WriteLine("Base"); }
}
class Derived : Base
{
    public override void Foo() { Console.WriteLine("Derived"); }
}
public static void Main()
{
    Derived d = new Derived();
    typeof(Base).GetMethod("Foo").Invoke(d, null);
    Console.ReadLine();
}

此代码始终显示派生"...

This code always shows 'Derived'...

推荐答案

你不能那样做,即使有反思.C# 中的多态性实际上保证了 Derived.Foo() 将始终被调用,即使在将 Derived 的实例转换回其基类时也是如此.

You can't do that, even with reflection. Polymorphism in C# actually guarantees that Derived.Foo() will always be called, even on an instance of Derived cast back to its base class.

Derived 实例调用 Base.Foo() 的唯一方法是显式使其可从 Derived 类访问:

The only way to call Base.Foo() from a Derived instance is to explicitly make it accessible from the Derived class:

class Derived : Base
{
    public override void Foo()
    {
        Console.WriteLine("Derived");
    }

    public void BaseFoo()
    {
        base.Foo();
    }
}

这篇关于使用反射调用覆盖的基本方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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