舉例如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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(); } } /* 《程式語言教學誌》的範例程式 檔名:class16.cs 功能:示範 C# 程式 作者:張凱慶 時間:西元 2013 年 6 月 */ |
Demo 只有一個 private 建構子
2 | private Demo() {} |
因此無法從 Demo 以外的地方建立 Demo 物件,編譯會產生錯誤訊息

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

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