簡單說,建構子是一種特別的方法,也由於建構子的目的在於建立物件,因此建構子不需要宣告回傳值 (return value) 。此外自訂類別沒有寫建構子的話,編譯器 (compiler) 也會提供一個預設版本的建構子。
舉例如下
class Demo {
int a;
int b;
Demo() {
a = 11;
b = 22;
}
int DoSomething() {
return a + b;
}
static void Main() {
Demo d = new Demo();
System.Console.WriteLine(d.DoSomething());
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:class03.cs
功能:示範 C# 程式
作者:張凱慶
時間:西元 2013 年 6 月 */建構子的名稱與類別名稱相同,此例為沒有參數 (parameter) 的建構子
Demo() {
a = 11;
b = 22;
}編譯執行,結果如下

下例示範有參數的建構子
class Demo {
int a;
int b;
Demo() {
a = 11;
b = 22;
}
Demo(int pa, int pb) {
a = pa;
b = pb;
}
int DoSomething() {
return a + b;
}
static void Main() {
Demo d1 = new Demo();
System.Console.WriteLine(d1.DoSomething());
Demo d2 = new Demo(25, 12);
System.Console.WriteLine(d2.DoSomething());
}
}
/* 《程式語言教學誌》的範例程式
http://pydoing.blogspot.com/
檔名:class04.cs
功能:示範 C# 程式
作者:張凱慶
時間:西元 2013 年 6 月 */建構子如同方法,可以有不同的參數版本,此例除了沒有參數的建構子外,我們還寫了一個有兩個參數的建構子
Demo(int pa, int pb) {
a = pa;
b = pb;
}編譯執行,結果如下

注意這裡的參數名稱與屬性 (property) 名稱並不相同,如果參數想要用與屬性相同識別字的話,屬性前就得加上 this ,例如
Demo(int a, int b) {
this.a = a;
this.b = b;
}| 中英文術語對照 | |
|---|---|
| 建構子 | constructor |
| 類別 | class |
| 物件 | object |
| 方法 | method |
| 回傳值 | return value |
| 編譯器 | compiler |
| 參數 | parameter |
| 屬性 | property |
您可以繼續參考
類別
相關目錄
回 C# 快速導覽
回 C# 教材
回首頁
參考資料
Standard ECMA-334 C# Language Specification
msdn: 建構函式 (C# 程式設計手冊)
沒有留言:
張貼留言