物件建立需初始化屬性。基本型別直接賦值,參考型別需 new。最基本 string name = new string("Lu xiaofeng");。建構子:同名於類別、無回傳型別 (甚至不可寫 void)、可多載。
public Person() { name="Lu xiaofeng"; sex="man"; age=22; weight=99; }
public Person(string name,string sex,int age,double weight) { this.name=name; this.sex=sex; this.age=age; this.weight=weight; }
兩種建構子建立物件屬性不同:
當參數名與欄位名相同時,this 指定「目前實例」的欄位。若移除 this,參數將自我指派導致欄位未初始化。
public Person(string name,string sex,int age,double weight) { name=name; sex=sex; age=age; weight=weight; } // 錯誤:參數自我指派
靜態成員/屬性/欄位初始化中不可使用 this。