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

C# this 關鍵字完整指南:實例參考、建構函式鏈結、索引子與效能迷思

     編輯:關於C語言

this 的四大核心用法

場景語法說明
消除名稱衝突this.field = param;建構函式/方法參數與欄位同名時
建構函式鏈結this(...)避免重複初始化邏輯
索引子定義public T this[int i] { get; set; }讓類別支援陣列式存取
傳遞自身參考Other.Method(this);雙向關聯、Visitor 模式、流式介面

完整範例


using System;

class Temperature {
    private double _celsius;
    private string _cache;

    public double Celsius {
        get => _celsius;
        private set => _celsius = value;
    }

    // 1. 消除衝突
    public Temperature(double celsius) {
        this._celsius = celsius; // 參數 celsius vs 欄位 _celsius
    }

    // 2. 複本建構函式 + 自身比較
    public Temperature(Temperature other) {
        if (this != other) { // 3. 判斷是否為同一實例
            _celsius = other.Celsius;
        }
    }

    // 4. 傳遞自身給轉換器
    public override string ToString() =>
        $"{_celsius}°C = {Converter.ToFahrenheit(this)}°F";

    // 5. 效能測試:this. 欄位 vs 直接欄位
    public string TestWithThis() {
        long start = Environment.TickCount;
        for (int i = 0; i < 10_000_000; i++) this._cache = i.ToString();
        return $"With this: {Environment.TickCount - start} ms";
    }
    public string TestWithoutThis() {
        long start = Environment.TickCount;
        for (int i = 0; i < 10_000_000; i++) _cache = i.ToString();
        return $"Without this: {Environment.TickCount - start} ms";
    }
}

static class Converter {
    public static double ToFahrenheit(Temperature t) => 1.8 * t.Celsius + 32;
}

class Program {
    static void Main() {
        Temperature t = new Temperature(37.5);
        Console.WriteLine(t); // 37.5°C = 99.5°F
        Console.WriteLine(t.TestWithThis());    // ~4375 ms
        Console.WriteLine(t.TestWithoutThis()); // ~4406 ms (差異可忽略)
        Console.ReadKey();
    }
}

關鍵限制

  • 靜態成員不可用 this:靜態方法/屬性/欄位無實例語境
  • this 是唯讀:不能 this = other、this++ 等修改
  • 結構體中 this:對應實例變數本身(值型別),修改會影響複製體

進階:結構體中的 this 語意


struct Point {
    public int X, Y;
    public void Reset() {
        // 結構體方法中 this 為值型別參考(ref)
        this = new Point(); // 等同 X=0; Y=0;
    }
    public void Translate(int dx, int dy) {
        this = new Point(X + dx, Y + dy); // 重新指派整個結構體
    }
}

效能迷思實測

範例中 TestWithThis vs TestWithoutThis 差異 < 1%,屬於雜訊範圍。JIT 編譯器會最佳化掉 this. 前綴。結論:可讀性優先,無需為 this. 效能擔憂。

流式介面模式


class QueryBuilder {
    private string _table, _where;
    public QueryBuilder From(string table) { _table = table; return this; }
    public QueryBuilder Where(string condition) { _where = condition; return this; }
    public string Build() => $"SELECT * FROM {_table} WHERE {_where};";
}

// 用法
var sql = new QueryBuilder().From("Users").Where("Age > 18").Build();

回傳 this 實現方法鏈結,廣泛用於建構器、LINQ、設定物件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved