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();
}
}
}