本文實例為大家分享了C# this關鍵字的四種用法,供大家參考,具體內容如下
用法一 this代表當前實例,用this.顯式調用一個類的方法和成員
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
namespace Demo { public class Test { private string scope = "全局變量" ; public string getResult() { string scope = "局部變量" ; // 在這里,this代表Test的實例,所以this.scope指向的是全局變量,scope所訪問的是局部變量 return this .scope + "-" + scope; } } class Program { static void Main( string [] args) { try { Test test = new Test(); Console.WriteLine(test.getResult()); } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.ReadLine(); } } } |
用法二 通過this實現原始類型的擴展(下一篇詳解)
用法三 通過this實現索引器,可用于優化程序性能(下一篇詳解)
用法四 用this串聯構造函數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
namespace Demo { public class Test { public Test() { Console.WriteLine( "無參構造函數" ); } // 這里的this()指向的是Test()無參構造函數 // 相當于繼承了無參構造函數 public Test( string text) : this () { // 程序進來后會先執行Test()無參函數,然后繼續往下邊執行 Console.WriteLine(text); Console.WriteLine( "有參構造函數" ); } } class Program { static void Main( string [] args) { try { Test test = new Test( "張三" ); } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.ReadLine(); } } } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。