私人建構函式是特殊的實例建構函式。 它通常用於只包含靜態成員的類別中。 如果類別有一或多個私人建構函式且沒有公用建構函式,其他類別(巢狀類別除外)就無法建立這個類別的實例。 例如:
class NLog
{
// Private Constructor:
private NLog() { }
public static double e = Math.E; //2.71828...
}
空建構函式的宣告可防止自動產生無參數建構函式。 請注意,如果您未搭配建構函式使用存取修飾詞,預設仍會是私用的。 不過,私 有時會明確用作修飾子,以表示類別無法被實例化。
當沒有任何實例欄位或方法,例如 Math 類別,或呼叫方法來取得類別的實例時,會使用私人建構函式來防止建立類別的實例。 如果類別中的所有方法都是靜態的,請考慮讓完整的類別成為靜態。 如需詳細資訊,請參閱 靜態類別和靜態類別成員。
範例
以下是使用私用建構函式的類別範例。
public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}
class TestCounter
{
static void Main()
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
Console.WriteLine($"New count: {Counter.currentCount}");
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
// Output: New count: 101
請注意,如果您從範例取消批注下列語句,它會產生錯誤,因為建構函式因為其保護層級而無法存取:
// Counter aCounter = new Counter(); // Error