舉例如下
class Demo {
private Demo() {}
public void DoSomething() {
System.Console.WriteLine("There is no spoon.");
}
}
class DemoTest {
static void Main() {
Demo d = new Demo();
d.DoSomething();
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:class16.cs
功能:示範 C# 程式
作者:張凱慶
時間:西元 2013 年 6 月 */Demo 只有一個 private 建構子
private Demo() {}因此無法從 Demo 以外的地方建立 Demo 物件,編譯會產生錯誤訊息

private 建構子比較常應用在具有 static 成員的類別,因為使用 static 成員是直接由類別名稱呼叫,不需要建立物件,例如
class Demo {
private Demo() {}
public static void DoSomething() {
System.Console.WriteLine("There is no spoon.");
}
}
class DemoTest {
static void Main() {
Demo.DoSomething();
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:class17.cs
功能:示範 C# 程式
作者:張凱慶
時間:西元 2013 年 6 月 */編譯執行,結果如下

| 中英文術語對照 | |
|---|---|
| 建構子 | constructor |
| 類別 | class |
| 物件 | object |
您可以繼續參考
類別
相關目錄
回 C# 快速導覽
回 C# 教材
回首頁
參考資料
Standard ECMA-334 C# Language Specification
msdn: 私用建構函式 (C# 程式設計手冊)
沒有留言:
張貼留言