C# 中的『表達式主體成員』寫法

在 C# 中,「表達式主體成員(Expression-bodied members)」是一種簡潔寫法,能讓屬性、方法、建構子、解構子,甚至是 finalizer 都以 => 取代傳統的 { return ...; } 區塊。這在 C# 6 開始引入,後續版本(C# 7、8 之後)擴充了支援範圍。

public class DatabaseContext : IDisposable
{
    private readonly IDbConnection _connection;

    public DatabaseContext(string connectionString)
    {
        _connection = new SqlConnection(connectionString);
    }

    public IDbConnection Connection => _connection;

    public void Dispose()
    {
        _connection?.Dispose();
    }
}

public IDbConnection Connection => _connection; 語法說明

✅ 語法介紹

public IDbConnection Connection => _connection;

這是 C# 中的 表達式主體成員(Expression-bodied member) 寫法,代表只讀屬性(唯有 getter)的一種簡潔寫法。


✅ 等價寫法

等同於以下傳統屬性寫法:

public IDbConnection Connection
{
    get
    {
        return _connection;
    }
}

✅ 語法拆解

元件 說明
public 公有屬性,可供外部存取
IDbConnection 屬性的資料型別
Connection 屬性名稱
=> _connection; 使用「箭號運算子」定義 getter,回傳 _connection 欄位的值

✅ 特點與用途

  • 🔒 唯讀屬性:無 setter,外部無法修改。
  • 🧼 簡潔語法:適合簡單邏輯、不需額外處理的屬性。
  • 🧱 封裝性強:對外公開 _connection,但仍保有內部控制權。
  • 🔄 可讀性高:適合用於包裝欄位或設計只讀服務接口。

✅ 實際使用情境

範例:資料庫上下文類別(DatabaseContext

public class DatabaseContext : IDisposable
{
    private readonly IDbConnection _connection;

    public DatabaseContext(string connectionString)
    {
        _connection = new SqlConnection(connectionString);
    }

    public IDbConnection Connection => _connection;

    public void Dispose()
    {
        _connection?.Dispose();
    }
}

📌 Connection 屬性讓使用者可以安全地存取資料庫連線,卻無法修改或重設 _connection

using System;

public class Person
{
    private string _name;
    private int _score;
    private string[] _notes = new[] { "Note1", "Note2", "Note3" };

    // 建構子
    public Person(string name) => _name = name;
    // 傳統寫法:
    // public Person(string name) { _name = name; }

    // Finalizer
    ~Person() => Console.WriteLine("Person finalized!");
    // 傳統寫法:
    // ~Person() { Console.WriteLine("Person finalized!"); }

    // 方法
    public string GetGreeting() => $"Hello, {_name}!";
    // 傳統寫法:
    // public string GetGreeting() { return $"Hello, {_name}!"; }

    // Getter only 屬性
    public int NameLength => _name.Length;
    // 傳統寫法:
    // public int NameLength { get { return _name.Length; } }

    // Getter + Setter 屬性
    public int Score
    {
        get => _score;
        set => _score = value;
    }
    // 傳統寫法:
    // public int Score
    // {
    //     get { return _score; }
    //     set { _score = value; }
    // }

    // 索引子(Indexer)
    public string this[int index]
    {
        get => _notes[index];
        set => _notes[index] = value;
    }
    // 傳統寫法:
    // public string this[int index]
    // {
    //     get { return _notes[index]; }
    //     set { _notes[index] = value; }
    // }

    // 解構方法(Deconstructor)
    public void Deconstruct(out string name, out int score) => (name, score) = (_name, _score);
    // 傳統寫法:
    // public void Deconstruct(out string name, out int score)
    // {
    //     name = _name;
    //     score = _score;
    // }

    // Operator overloading
    public static Person operator +(Person a, Person b) => new Person(a._name + " & " + b._name);
    // 傳統寫法:
    // public static Person operator +(Person a, Person b)
    // {
    //     return new Person(a._name + " & " + b._name);
    // }
}
Author image
關於 Richard Zheng
您已成功訂閱 Richard's NoteBook
歡迎回來!您已成功登入。
無法讓您登入。請再試一次。