Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从另一个派生类对象调用派生类虚方法_C#_Oop_Virtual - Fatal编程技术网

C# 如何从另一个派生类对象调用派生类虚方法

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

下面提到的场景将以良好的方式消除这种情况。我愿意调用xDerived1类虚拟方法。虽然我能够调用xBase类方法和xDerived2类方法

((xDerived1)xDer2.myMethod()//重写无效方法

请帮帮我

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()?