本文實(shí)例為大家分享了C# this關(guān)鍵字的四種用法,供大家參考,具體內(nèi)容如下
用法一 this代表當(dāng)前實(shí)例,用this.顯式調(diào)用一個(gè)類的方法和成員
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的實(shí)例,所以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實(shí)現(xiàn)原始類型的擴(kuò)展(下一篇詳解)
用法三 通過this實(shí)現(xiàn)索引器,可用于優(yōu)化程序性能(下一篇詳解)
用法四 用this串聯(lián)構(gòu)造函數(shù)
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( "無參構(gòu)造函數(shù)" ); } // 這里的this()指向的是Test()無參構(gòu)造函數(shù) // 相當(dāng)于繼承了無參構(gòu)造函數(shù) public Test( string text) : this () { // 程序進(jìn)來后會(huì)先執(zhí)行Test()無參函數(shù),然后繼續(xù)往下邊執(zhí)行 Console.WriteLine(text); Console.WriteLine( "有參構(gòu)造函數(shù)" ); } } class Program { static void Main( string [] args) { try { Test test = new Test( "張三" ); } catch (Exception ex) { Console.WriteLine(ex); } finally { Console.ReadLine(); } } } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。