C# this關(guān)鍵字的四種用法
本文實例為大家分享了C# this關(guān)鍵字的四種用法,供大家參考,具體內(nèi)容如下
用法一 this代表當前實例,用this.顯式調(diào)用一個類的方法和成員
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實現(xiàn)原始類型的擴展(下一篇詳解)
用法三 通過this實現(xiàn)索引器,可用于優(yōu)化程序性能(下一篇詳解)
用法四 用this串聯(lián)構(gòu)造函數(shù)
namespace Demo { public class Test { public Test() { Console.WriteLine("無參構(gòu)造函數(shù)"); } // 這里的this()指向的是Test()無參構(gòu)造函數(shù) // 相當于繼承了無參構(gòu)造函數(shù) public Test(string text) : this() { // 程序進來后會先執(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(); } } } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C#實現(xiàn)把txt文本數(shù)據(jù)快速讀取到excel中
這篇文章主要介紹了C#實現(xiàn)把txt文本數(shù)據(jù)快速讀取到excel中,本文直接給出示例代碼,需要的朋友可以參考下2015-06-06在類庫或winform項目中打開另一個winform項目窗體的方法
這篇文章主要介紹了在類庫或winform項目中打開另一個winform項目窗體的方法,可以實現(xiàn)Winform項目間窗體的調(diào)用,在進行Winform項目開發(fā)中非常具有實用價值,需要的朋友可以參考下2014-11-11Graphics.DrawImage繪制的圖像變大的原因分析及解決
這篇文章主要介紹了Graphics.DrawImage繪制的圖像變大的原因分析及解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11C# winform 請求http的實現(xiàn)(get,post)
本文主要介紹了C# winform 請求http的實現(xiàn)(get,post),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2022-06-06