跳轉到內容

C# 程式設計/封裝2

來自華夏公益教科書,自由的教科書

屬性封裝了對物件狀態的控制。

例如,以下Customer 類封裝了客戶的姓名

public class Customer
{ 
  // "private" prevents access of _name outside the Customer class:
  private string _name;   

  // The following property allows programmatic changes to _name:
  public string Name
  {
      set { this._name = value; }
      get { return this._name; }
  }
}

上面的Name 屬性包含三個重要部分:宣告、設定訪問器獲取訪問器

屬性宣告

[編輯 | 編輯原始碼]
<access modifier> <type> <property name> 
public string Name

訪問修飾符決定了誰可以操作這些資料。屬性可以被限定為publicprivateprotectedinternal

型別決定了它可以接受或返回的型別。

屬性名稱聲明瞭用於訪問屬性的名稱。

訪問器

[編輯 | 編輯原始碼]

使用設定訪問器設定Customer 類中的Name 屬性,它使用set 關鍵字定義。

類似地,get 關鍵字建立一個獲取訪問器,用於封裝當客戶端檢索屬性值時要執行的邏輯。

上面,簡單的設定訪問器獲取訪問器使屬性的行為非常類似於簡單的欄位。這可能不是我們想要的。如果不是,我們可以新增邏輯來檢查傳遞到set 訪問器中的值

public string Name
       {
           set { 
                 if (value != null)
                    this._name = value;
               }
           get {                   
                 if (this._name != null)
                    return this._name;
                 else
                    return "John Doe";
               }
       }

上面,如果客戶端請求將值設定為null,則設定訪問器不會更改欄位。此外,如果_name 欄位尚未設定,則獲取訪問器將返回預設值。

使用屬性

[編輯 | 編輯原始碼]

客戶端可以使用屬性,就像使用簡單的類欄位一樣

Customer customer = new Customer();

// this will not set the data.
customer.Name = "";

// since the field is not yet set, this will print out: "John Doe"
System.Console.WriteLine(customer.Name);

customer.Name = "Marissa";
System.Console.WriteLine(customer.Name);

上面的程式碼列印以下內容

John Doe
Marissa

訪問級別

[編輯 | 編輯原始碼]

C# 提供的各種訪問級別,從最公開到最不公開

訪問級別 使用限制
public 無。
internal 包含的程式集。
protected internal 包含的程式集或從包含類派生的型別。
protected 包含的類或從中派生的型別。
private 包含的型別。

如果未指定訪問級別,則使用預設級別。它們是

型別 預設訪問級別
namespace public(也是唯一允許的)
enum public
class private
interface public
struct private
(其他) internal

注意:名稱空間級別元素(例如直接在名稱空間下宣告的類)不能宣告為比 internal 更嚴格的級別。

華夏公益教科書