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

C# 語法精進:this 關鍵字完整用法指南(一)—— 實例參考、建構函式鏈、索引子與擴充方法

     編輯:關於C語言

this 核心含義

this 代表目前類別的執行個體。三大主要用途:

  1. 限定被同名參數/區域變數隱藏的實例成員
  2. 將目前物件作為參數傳遞給其他方法
  3. 宣告索引子、擴充方法第一個參數修飾詞

用法一:區分同名參數與欄位

public class Employee
{
    private string _name;
    private string _alias;

    public Employee(string name, string alias)
    {
        // 參數 name/alias 隱藏了欄位 _name/_alias
        // 使用 this 明確指派給實例欄位
        this._name = name;
        this._alias = alias;
    }
}

用法二:傳遞目前物件實例

public class TaxCalculator
{
    public decimal Calculate(Employee emp) { /* ... */ return 0; }
}

public class Employee
{
    public void ProcessTax()
    {
        var calculator = new TaxCalculator();
        // 將 this (目前 Employee 實例) 傳遞給計算器
        decimal tax = calculator.Calculate(this);
    }
}

用法三:宣告索引子

public class ScoreBoard
{
    private int[] _scores = new int[100];
    
    // 索引子:讓類別像陣列一樣被存取
    public int this[int index]
    {
        get => _scores[index];
        set => _scores[index] = value;
    }
}

// 使用方式
var board = new ScoreBoard();
board[0] = 95;     // 呼叫 set
int score = board[0]; // 呼叫 get

用法四:擴充方法第一個參數

public static class StringExtensions
{
    // this string str 表示擴充 string 型別
    public static bool IsValidEmail(this string str)
    {
        return System.Text.RegularExpressions.Regex.IsMatch(
            str, @"^[^@\s]+@[^@\s]+\.[^@\s]+$");
    }
}

// 使用方式:像實例方法一樣呼叫
string email = "test@example.com";
bool valid = email.IsValidEmail(); // 實際呼叫 StringExtensions.IsValidEmail(email)

用法五:建構函式鏈

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }
    public string Label { get; set; }

    // 主要建構函式
    public Point(int x, int y, string label)
    {
        X = x; Y = y; Label = label;
    }

    // 透過 this() 呼叫主要建構函式,避免重複程式碼
    public Point(int x, int y) : this(x, y, "Default") { }
    public Point() : this(0, 0, "Origin") { }
}

重要限制:靜態內容中不可用

public class Demo
{
    public static void StaticMethod()
    {
        // 錯誤 CS0026:靜態方法中無法使用 this
        // Console.WriteLine(this.ToString()); 
    }
    
    public void InstanceMethod()
    {
        // 正確:實例方法中 this 可用
        Console.WriteLine(this.GetType().Name);
    }
}

this vs base 快速比較

特性thisbase
指向對象目前實例基底類別實例部分
建構函式呼叫this(...) 同類別其他建構函式base(...) 基底類別建構函式
成員存取目前類別成員(含隱藏基底的)基底類別成員(穿透隱藏)
靜態方法禁止禁止
索引子定義索引子語法無
擴充方法第一個參數修飾詞無

最佳實踐建議

  • 建構函式參數與欄位同名時,**慣用底線前綴欄位**(_name)而非依賴 this.name,提升可讀性
  • 索引子提供直觀存取介面,但避免在索引子中執行複雜邏輯
  • 擴充方法命名空間需 using 才生效,設計時考慮可發現性
  • 建構函式鏈:永遠讓參數最完整的建構函式為「主要」,其他透過 this() 呼叫
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved