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

C# 屬性完整教學:封裝欄位、唯讀、唯寫與自動實作屬性

     編輯:關於C語言

為什麼需要屬性?

傳統做法需撰寫 GetXxx()/SetXxx() 方法封裝私有欄位。C# 屬性提供語法糖,讓呼叫端如同存取公開欄位般自然,同時保留封裝彈性 (驗證、通知、延遲載入等)。

基本語法

public class PropertyHolder
{
    private int someProperty = 0;  // 背景欄位

    public int SomeProperty        // 屬性名稱慣用 PascalCase
    {
        get { return someProperty; }
        set { someProperty = value; }  // value 為隱含參數
    }
}

// 使用方式
PropertyHolder ph = new PropertyHolder();
ph.SomeProperty = 5;          // 呼叫 set
Console.WriteLine(ph.SomeProperty); // 呼叫 get

唯讀屬性

public class PropertyHolder
{
    private int someProperty;
    public PropertyHolder(int val) { someProperty = val; }

    public int SomeProperty
    {
        get { return someProperty; }  // 僅提供 get
    }
}

// 呼叫端
PropertyHolder ph = new PropertyHolder(5);
Console.WriteLine(ph.SomeProperty); // OK
// ph.SomeProperty = 7; // 編譯錯誤:無 set 存取子

唯寫屬性

public class PropertyHolder
{
    private int someProperty;
    public int SomeProperty
    {
        set
        {
            someProperty = value;
            Console.WriteLine("Value set to {0}", someProperty);
        }
    }
}

// 呼叫端
PropertyHolder ph = new PropertyHolder();
ph.SomeProperty = 5; // 僅能設定,無法讀取

自動實作屬性 (C# 3.0+)

編譯器自動產生背景欄位,適合無額外邏輯的單純封裝:

public class Person
{
    public string Name { get; set; }
    public int Age { get; private set; }  // 可分別設定存取層級
}

屬性 vs 欄位:何時用哪個?

情境建議
公開 API、需驗證/通知/延遲載入、序列化控制屬性
內部實作細節、高效能熱路徑、無封裝需求私有/受保護欄位

進階技巧

  • 初始化:public int Score { get; set; } = 100; (C# 6+)
  • 運算式主體:public int Double => value * 2; (唯讀)
  • init 存取子 (C# 9+):public string Id { get; init; } 僅允許物件初始化器設定。
  • required (C# 11+):public required string Email { get; set; } 強制建構時指定。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved