2017年9月5日 星期二

[C#] this 用法


this 這個關鍵字,常常可以在程式碼中看到。
主要是提供使用者  在編寫 method 中,去存取 class 等級的變數


class ExampleClass
{
public int num = 100;
public void ExMethod()
{
int num2 = 0;
MessageBox.Show(string.Format("num2 = {0}, num = {1}", num2, this.num));
// num2 = 0, num = 100
num2 = this.num;
MessageBox.Show(string.Format("num2 = {0}, num = {1}", num2, this.num));
// num2 = 100, num = 100
}
}
view raw gistfile1.txt hosted with ❤ by GitHub


由上面範例,可以看到,透過this, 就可以存取宣告於 class 的變數

沒有留言:

張貼留言