C#面向对象的程序设计问题 - 重写方法

ori*_*ari 0 c# oop polymorphism casting

在C#中考虑以下代码:

    public class A
    {
        public A()
        {
            Console.WriteLine("A");
        }
        public virtual void One()
        {
            Console.WriteLine("One of A");
        }
        public virtual void Two()
        {
            One();
        }
    }

    public class B : A
    {
        public B()
        {
            Console.WriteLine("B");
        }
        public override void One()
        {
            Console.WriteLine("One of B");
        }
        public override void Two()
        {
            Console.WriteLine("Two of B");
        }
        public void Three()
        {
            base.Two();
        }
    }
Run Code Online (Sandbox Code Playgroud)

主要:

A a3 = new B(); //"A" and then "B"
a3.Two();' //"Two of B"
((B)a3).Three(); //"One of B"
Run Code Online (Sandbox Code Playgroud)

为什么主程序中的最后一行写"B之一"?为什么当它执行One()时它会转到B的One()?

D S*_*ley 8

细分每个方法调用的内容 -

((B)a3).Three(); 
Run Code Online (Sandbox Code Playgroud)

电话

B.Three();
Run Code Online (Sandbox Code Playgroud)

哪个叫

A.Two();
Run Code Online (Sandbox Code Playgroud)

哪个叫

A.One();
Run Code Online (Sandbox Code Playgroud)

但它A.One虚拟的,这意味着系统必须在运行时查看对象的实际类型以确定 将调用哪个 One.

由于引用的对象a3是a B(即使您声明A变量引用),B.One()也会被调用.