Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.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#_Clr - Fatal编程技术网

C# 为什么要调用这个虚拟方法?

C# 为什么要调用这个虚拟方法?,c#,clr,C#,Clr,我编写了一个基类和两个派生类: class Base { public virtual void fn() { Console.WriteLine("base fn"); } } class Derived1 : Base { public override void fn() { Console.WriteLine("derived1 fn"

我编写了一个基类和两个派生类:

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

class Derived1 : Base
    {
        public override void fn()
        {
            Console.WriteLine("derived1 fn");
        }
    }

class Derived2 : Derived1
    {
        public new void fn()
        {
            Console.WriteLine("derived2 fn");
        }
    }
然后创建一个由基变量引用的derived2实例。然后调用fn()方法:

结果是调用了Derived1类的fn()

据我所知,如果调用虚拟方法,CLR将在运行时类型的方法表中查找该方法,该方法为Derived2;如果调用了非虚方法,ClR将在变量类型为Base的方法表中查找它。但为什么它会调用Derived1的方法呢


答案“因为Derived1覆盖了Base的fn()”不足以澄清我的困惑。请提供更多详细信息。

虚拟方法调用的解释如下所示:

调用虚拟方法时,对象的运行时类型为 已检查是否存在覆盖成员most中的覆盖成员 派生类被称为,如果不是,则可能是原始成员 派生类已重写该成员


由于Derived2类使用“new”关键字隐藏基本方法,因此CLR将在派生最多的类中查找重写成员,即Derived1并执行其方法

我做了另一个测试:
class Program
    {
        static void Main(string[] args)
        {
            Base b = new Derived2();
            b.fn();
            Console.Read();
        }
    }