C# 的「表達式主體成員」寫法

在 C# 中,「表達式主體成員(Expression-bodied members)」可以用 => 簡化傳統的 { return ...; } 區塊。C# 6 先引入這項語法,之後的 C# 7、8 再擴大支援範圍,可用在屬性、方法、建構子、解構子與 finalizer。

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
About me 喜歡爬山,瑜伽,溜冰,喜歡新奇的事,最喜歡的還是寫程式帶來的成就感,對於資訊會不斷的出現新事物也能抱持好奇與熱忱。近期開始將學習的心得寫在Blog,發現思路更清晰也加深了記憶。 紙上得來終覺淺,絕知此事要躬行