C#拾遺系列(3):建構函式

來源:互聯網
上載者:User

 

1. 主要示範建構函式的繼承

 

  •   聲明空建構函式可阻止自動產生預設建構函式。
  •   如果您不對建構函式使用存取修飾詞,則在預設情況下它仍為私人建構函式。
  •   通常顯式地使用 private 修飾符來清楚地表明該類不能被執行個體化。

 

2. 靜態建構函式

  • 靜態建構函式具有以下特點:
  • 靜態建構函式既沒有存取修飾詞,也沒有參數。
  • 在建立第一個執行個體或引用任何靜態成員之前,將自動調用靜態建構函式來初始化類。
  • 無法直接調用靜態建構函式。
  • 在程式中,使用者無法控制何時執行靜態建構函式。
  • 靜態建構函式的典型用途是:當類使用記錄檔時,將使用這種建構函式向記錄檔中寫入項。
  • 靜態建構函式在為Unmanaged 程式碼建立封裝類時也很有用

3. 樣本:

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

 

//Description: 建構函式測試

 

namespace NetTest

{

   public class Father

    {

 

       public Father()

       {

           Console.Out.WriteLine("Father say");

       }

        public static Father()

        { }

        */

 

       public Father(string s)

       {

           Console.Out.WriteLine(s + ":Father Say");

       }

    }

 

   public class Son:Father

   { 

       /*

       //調用父無參建構函式類建構函式

       public Son()

       {

           Console.Out.WriteLine("Son say");

       }

        */   

       public Son(string s)

       {

           Console.Out.WriteLine("good son say:");      

       }

 

       /* base顯示調用父類建構函式

       public Son()

           : base("jack")

       {

           Console.Out.WriteLine("Son say");

       }

       */

 

       /*子類會隱示調用父類無參建構函式*/

       /*this調用自身重載的建構函式*/

       public Son()

           : this("call myself another constructor")

       {             

           Console.Out.WriteLine("above sentence calling myself");      

       }     

   }

 

   public class TestConstructor

   {

 

       public void Test()

       {

           new Son();       

       }

   }

}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.