類別封裝屬性與方法,面向物件將一切視為物件,世間無兩片相同葉子,故建立物件時需對屬性初始化。基本型別宣告:int myint = 3;。物件型別需用 new 建立。最基本 string:string name = new string("Lu xiaofeng"); 調用時記憶體載入 name = "Lu xiaofeng"。物件型別必須建立後才能使用,否則錯誤:可能未初始化變數。重要概念:建構函式,每個類別有預設建構函式初始化資料。建構函式形式:

建構函式名稱必須與類別名稱相同,無回傳值,不允許 void 修飾。但允許多載:一個類別可有多個不同建構函式滿足建立物件。例 Person 類別兩個建構函式:public Person() {} 及 public Person(string name, string sex, int age, double weight)。宣告 Person myman = new Person(); 也可用另一建構函式 Person niu = new Person("name", "man", 22, 99);,兩物件屬性不同。

看兩建構函式內容:
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,用來指定「這個」。尤其當欄位名稱與參數名稱相同:
public string name; public string sex; public int age; public double weight;
public Person(string name, string sex, int age, double weight) { ... }
可將參數換成其他名稱 myname, mysex, myage, myweight 不影響結果。但若移除 this:
public Person(string name, string sex, int age, double weight) {
name = name; sex = sex; age = age; weight = weight;
}
建立兩物件測試:
Person newman = new Person("lixiao", "woman", 11, 88);
Console.WriteLine("name={0}, sex={1}, age={2}, weight={3}", newman.name, newman.sex, newman.age, newman.weight);
Person another = new Person();
Console.WriteLine("name={0}, sex={1}, age={2}, weight={3}", another.name, another.sex, another.age, another.weight);
移除 this 後效果:

this 關鍵字參考被存取成員所在當前實例。靜態成員函式無 this 指標。this 可用於建構函式、實例方法、實例存取子存取成員。不能在靜態方法、靜態屬性存取子、欄位宣告初始化中使用 this。
this 作為實值型別表示正在建構物件本身參考。this 表示呼叫該方法物件參考。this 表示正在建構結構參考。this 表示呼叫該方法結構參考。