C# 如何从另一个派生类对象调用派生类虚方法
下面提到的场景将以良好的方式消除这种情况。我愿意调用xDerived1类虚拟方法。虽然我能够调用xBase类方法和xDerived2类方法 ((xDerived1)xDer2.myMethod()//重写无效方法 请帮帮我C# 如何从另一个派生类对象调用派生类虚方法,c#,oop,virtual,C#,Oop,Virtual,下面提到的场景将以良好的方式消除这种情况。我愿意调用xDerived1类虚拟方法。虽然我能够调用xBase类方法和xDerived2类方法 ((xDerived1)xDer2.myMethod()//重写无效方法 请帮帮我 static void Main(string[] args) { xDerived2 xDer2 = new xDerived2(); xDer2.myMethod(); ((xBase
static void Main(string[] args)
{
xDerived2 xDer2 = new xDerived2();
xDer2.myMethod();
((xBase)xDer2).myMethod();
((xDerived1)xDer2).myMethod();
}
public class xBase
{
public virtual void myMethod()
{
Console.WriteLine("virtual void myMethod");
}
}
public class xDerived1 :xBase
{
public new virtual void myMethod()
{
Console.WriteLine("new virtual void myMethod");
}
}
public class xDerived2 : xDerived1
{
public override void myMethod()
{
Console.WriteLine("override void myMethod");
}
}
从
xbase
的实例调用xDerived1::myMethod
是不可能的。new
关键字导致定义新方法,因此xDerived::myMethod
与xbase::myMethod
完全分离。为了调用该方法,您需要向下转换到xDerived1
xbase local1 = ...;
xDerived1 local2 = local1 as xDerived;
if (local2 != null) {
local2.myMethod();
}
从
xbase
的实例调用xDerived1::myMethod
是不可能的。new
关键字导致定义新方法,因此xDerived::myMethod
与xbase::myMethod
完全分离。为了调用该方法,您需要向下转换到xDerived1
xbase local1 = ...;
xDerived1 local2 = local1 as xDerived;
if (local2 != null) {
local2.myMethod();
}
我得到了这个问题的解决方案,我们可以通过使用反射来调用它,如下所述:
xDerived2 child = new xDerived2();
Action parentPrint = (Action)Activator.CreateInstance(typeof(Action), child, typeof(xDerived1).GetMethod("myMethod").MethodHandle.GetFunctionPointer());
parentPrint.Invoke();
我得到了这个问题的解决方案,我们可以通过使用反射来调用它,如下所述:
xDerived2 child = new xDerived2();
Action parentPrint = (Action)Activator.CreateInstance(typeof(Action), child, typeof(xDerived1).GetMethod("myMethod").MethodHandle.GetFunctionPointer());
parentPrint.Invoke();
我想符合:由于myMethod()在xDerived2中被重写,并且在xDerived1中是虚拟的,假设没有使用“new”关键字,是否可以调用xDerived1::myMethod()?我想符合:由于myMethod()在xDerived2中被重写,并且在xDerived1中是虚拟的,假设没有使用“new”关键字,ti是否可以调用xDerived1::myMethod()?