用法一 this代表當前類的實例對象
namespace Demo { public class Test { private string scope = "全局變量"; public string getResult() { string scope = "局部變量"; // this代表Test的實例對象 // 所以this.scope對應的是全局變量 // scope對應的是getResult方法內的局部變量 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串聯構造函數
namespace Demo { public class Test { public Test() { Console.WriteLine("無參構造函數"); } // this()對應無參構造方法Test() // 先執行Test(),后執行Test(string text) public Test(string text) : this() { 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(); } } } }
用法三 為原始類型擴展方法