如何使用反射调用被派生类覆盖的基方法?
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();
}
此代码始终显示“派生”...
最佳答案
折腾了很久,终于找到比DynamicMethod更好的解决方案:
class CallOverride
{
public static void Test()
{
var obj = new Override();
var method = typeof(object).GetMethod("ToString");
var ftn = method.MethodHandle.GetFunctionPointer();
var func = (Func<string>)Activator.CreateInstance(typeof(Func<string>), obj, ftn);
Console.WriteLine(func());
}
}
class Override
{
public override string ToString()
{
return "Nope";
}
}
此解决方案使用委托(delegate)的标准构造函数签名:
public Delegate(object target, IntPtr ftn)
其中 target 是目标实例,ftn 是函数指针。 它直接使用基方法的函数指针调用它,因此委托(delegate)将指向实际的基方法,而不是重写的方法。
关于c# - 使用反射调用重写的基方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4357729/