Use reflection to invoke an overridden base method

2019-01-04 13:50发布

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'...

8条回答
Summer. ? 凉城
2楼-- · 2019-01-04 14:16

Maybe Kii was looking for something like this

class Base
{
    public virtual void Foo() 
    { 
        Console.WriteLine("Base"); 
    }
}

class Derived : Base
{
    // Change virtual with new
    // public override void Foo() { Console.WriteLine("Derived"); }
    public new void Foo() 
    { 
        Console.WriteLine("Derived"); 
    }
}

static void Main(string[] args)
{
    Derived d = new Derived();
    d.Foo();// Output: Derived

    typeof(Base).GetMethod("Foo").Invoke(d, null);// Output: Base

    // Or you can cast
    ((Base)d).Foo();// Output: base

    Console.ReadLine();
}
查看更多
孤傲高冷的网名
3楼-- · 2019-01-04 14:22

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.

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();
    }
}
查看更多
登录 后发表回答