the constructor in C# (面試題建構函式是否可以繼承和重載的解釋)

來源:互聯網
上載者:User

1.觀察兩個類

  class A
    {
        protected int i = 0;
        public A()
        {
            i = 1;
        }

        public void P()
        {
            System.Console.WriteLine("P:"+i.ToString());
        }

        public virtual void VP()
        {
            System.Console.WriteLine("VP in A:" + i.ToString());
        }
    }

    class B:A
    {
        public B()
        {
            i = 2;
        }

        public B(int i)// public B(int i) = public B(int i):base()
        {
            //this.i = i;
            //keep this section as empty, while the base constructor will be invoked
        }

        public override void VP()
        {            
            System.Console.WriteLine("VP in B:" + i.ToString());
            //base.VP();
        }

    } 

 

2.

            A b = new A();
            b.P();
            b.VP();
            Console.Read();
            //調用預設建構函式
            //調用虛方法
            //一切都很簡單而且美好

            A b1 = new B();
            b1.P();
            b1.VP();
            //調用衍生類別的建構函式 , 
            //衍生類別的建構函式調用基類的預設建構函式

            A b2 = new B(0);
            b1.P();
            b1.VP();
            //調用衍生類別中帶參數的建構函式時 public B(int i) = public B(int i):base()
            //先調用衍生類別的建構函式
            //衍生類別的建構函式調用基類的預設建構函式

//            有呼叫堆疊為證
//>    ConsoleApplication2.exe!ConsoleApplication2.A.A() 行 11    C#
//    ConsoleApplication2.exe!ConsoleApplication2.B.B() 行 30 + 0x8 位元組    C#
//    ConsoleApplication2.exe!ConsoleApplication2.Program.Main(string[] args = {string[0]}) 行 64 + 0x15 位元組    C#

            

 

結論: 

1建構函式無法用virtual和override修飾,會造成編譯錯誤
2父建構函式可以被修改,但不是重寫,也不是重載,而是在調用時注入了新函數的代碼 

3在同一繼承層次的同一個類中,建構函式可以重載

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.