使用反射来调用一个重写的基方法 [英] Use reflection to invoke an overridden base method

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

问题描述

如何使用反射调用由派生类中重写的基方法是什么?

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();
}

这code总是显示'衍生'......

This code always shows 'Derived'...

推荐答案

您不能做到这一点,即使是与反思。多态性在C#实际上确保了 Derived.Foo()总是被调用,即使对派生投退实例到它的基类。

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.

只有这样,才能称之为 Base.Foo()派生实例,显式地从访问在派生类:

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天全站免登陆