使用反射来调用一个重写的基方法重写、射来、方法

由网友(背着书包闯天下)分享简介:如何使用反射调用由派生类中重写的基方法是什么?How to use reflection call a base method that is overridden by derived class?class Base{public virtual void Foo() { Console.WriteLine(...

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

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();
    }
}
阅读全文

相关推荐

最新文章