new與override的用法

摘要:new與override的用法

    public partial class Form1 : Form
    {
        public class Father
        {
            public void A()
            {
                Debug.WriteLine("This is Father A()");
            }

            public virtual void B()
            {
                Debug.WriteLine("This is Father B()");
            }
        }

        class Child : Father
        {
            public new void A()
            {
                Debug.WriteLine("This is Child A()");
            }

            public override void B()
            {
                Debug.WriteLine("This is Child B()");
            }

            public Child()
            {
                base.A();   //This is Father A()
                A();    //This is Child A()
                Debug.WriteLine("");
                /*
                輸出結果:
                This is Father A()
                This is Child A()              
                */
            }
        }

        public Form1()
        {
            InitializeComponent();

            Child o = new Child();
            o.A();  //This is Child A()
            o.B();  //因為Child裡面有override void B(),所以This is Child B(),否則就是Father B()
            ((Father)o).A();    //This is Father A(),因為new,所以還是可以將o強制轉型,取得Father的A()
            ((Father)o).B();    //這還是Child B(),因為override,轉型無效,取不到Father B()
            /*
            輸出結果:
            This is Child A()
            This is Child B()
            This is Father A()
            This is Child B()
            */
        }
    }