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

C# this 關鍵字:四大使用情境、常數本質、視窗啟用範例與 C++ 指標差異

     編輯:關於C語言

this 僅限於建構函式、類別方法、結構方法、結構建構函式中使用,表示當前實例的參考。

四大使用情境

情境型別分類含義
類別建構函式值型別正在建構的物件參考
類別方法值型別呼叫該方法的物件參考
結構建構函式變數型別正在建構的結構參考
結構方法變數型別呼叫該方法的結構參考

基本用法


class A {
    public int X;
    public void Main() {
        X = 5;
        Console.WriteLine($"X={X}, this.X={this.X}"); // 相同
    }
}

重要特性

  • 內部為常數:this++、this-- 非法;但可作為回傳值。
  • 非指標:C++ 程式員請忘記 this->、::,C# 僅用 . 存取成員。

進階範例:階乘驗證與視窗啟用


// 階乘驗證
class Fact {
    int x;
    public int GetFact() {
        int save = x, a = 1;
        while (x > a) { a++; float t = this.x / a; x /= a; if ((float)x != t) return -1; }
        Swap(ref this.x, ref save); return save;
    }
}

// 視窗啟用追蹤
class Window {
    public Window[] Child = new Window[5];
    public bool HasChild, IsActive;
    public Window GetActiveWindow() {
        if (!HasChild) { IsActive = true; return this; }
        for (int i=0;i<5;i++) if (Child[i].IsActive) return Child[i];
        return this;
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved