首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 物件導向程式設計 (續):建構函式、this 參考與多載

     編輯:關於C語言

一、 建構函式

類別封裝屬性與方法,面向物件將一切視為物件,世間無兩片相同葉子,故建立物件時需對屬性初始化。基本型別宣告: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);,兩物件屬性不同。

二、 this 參考

看兩建構函式內容:

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。

  1. 類別建構函式中 this 作為實值型別表示正在建構物件本身參考。
  2. 類別方法中 this 表示呼叫該方法物件參考。
  3. 結構建構函式中 this 表示正在建構結構參考。
  4. 結構方法中 this 表示呼叫該方法結構參考。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved