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(); } } } }
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(); } } } }