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

C# this 關鍵字完整指南:四大使用場景、結構體語意差異、流暢介面與視窗啟用實例

     編輯:關於C#

this 四大合法使用場景

場景this 型別/語意說明
類別建構子值型別 (參考)指向正在建構的實例
類別方法/屬性/索引子/事件存取器值型別 (參考)指向呼叫該成員的實例
結構體建構子變數型別 (by-ref)指向正在建構的結構體變數 (可修改)
結構體方法變數型別 (by-ref)指向呼叫該方法的結構體變數 (可修改)
  • 除此之外使用 this 皆為編譯錯誤 (靜態方法、屬性初始化運算式、欄位初始化運算式等)。
  • this 為唯讀 (類別) 或 by-ref 唯讀 (結構體方法),不可指派、不可遞增/遞減。

基本用法:消除名稱衝突


class Person {
    string _name;
    public Person(string name) {
        _name = name;           // 區分參數與欄位
        // 或使用 this
        this._name = name;      // 明確指定實例欄位
    }
    public void SetName(string name) => this._name = name;
}

進階用法 1:建構子鏈委派


class Connection {
    public Connection(string host, int port) : this(host, port, 3000) { }
    public Connection(string host, int port, int timeout) {
        Host = host; Port = port; Timeout = timeout;
    }
    // this(...) 必須是第一條陳述式
}

進階用法 2:流暢介面 / 方法鏈


class StringBuilder {
    private readonly List _parts = new();
    public StringBuilder Append(string s) { _parts.Add(s); return this; }
    public StringBuilder AppendLine(string s) => Append(s + Environment.NewLine);
    public override string ToString() => string.Concat(_parts);
}

// 使用
var sb = new StringBuilder()
    .Append("Hello")
    .Append(" ")
    .AppendLine("World");

進階用法 3:索引子/運算子中存取實例


class Matrix {
    double[,] _data;
    public double this[int r, int c] {
        get => _data[r, c];
        set => _data[r, c] = value;
    }
    public static Matrix operator +(Matrix a, Matrix b) {
        var result = new Matrix(a.Rows, a.Cols);
        for (int i = 0; i < a.Rows; i++)
            for (int j = 0; j < a.Cols; j++)
                result[i, j] = a[i, j] + b[i, j]; // 此處無 this
        return result;
    }
}

實戰範例:視窗啟用狀態管理


class Window {
    public Window[] ChildWindows = new Window[5];
    public bool HasChildren;
    public bool IsActive;

    public Window GetActiveWindow() {
        if (!HasChildren) {
            IsActive = true;
            return this; // 回傳目前實例
        }
        for (int i = 0; i < 5; i++) {
            if (ChildWindows[i]?.IsActive == true)
                return ChildWindows[i]; // 回傳子視窗實例
        }
        return this; // 預設回傳自己
    }
}

階乘驗證範例:this 在演算法中的角色


class FactorialChecker {
    int _number;
    public FactorialChecker(int number) => _number = number;

    public int GetFactorialBase() {
        int original = _number;
        int divisor = 2;
        while (_number > 1) {
            if (_number % divisor != 0) return -1;
            _number /= divisor;
            divisor++;
        }
        // 注意:此演算法有缺陷,僅示範 this 用法
        _number = original; // 還原 (若需保留狀態)
        return divisor - 1;
    }
}

C++ 程式員遷移指南

C++C#差異
this->memberthis.member 或 member統一用點號,無箭頭運算子
Class::staticMemberClass.staticMember統一用點號,無範圍解析運算子
this 為指標this 為參考/by-ref不可指標運算,不可 delete this
建構子中 this 指標完整建構子中 this 可用,但虛擬呼叫解析為基類別版本衍生類別尚未初始化

常見錯誤

  • static void M() { var x = this; } → CS0026: 靜態方法不可用 this。
  • int x = this++; → CS0063: this 不可遞增。
  • 結構體方法中 this = new Struct(); → 允許 (C# 7.2+),但會複製整個結構體。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved