C# this關鍵字的四種用法

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

用法三  爲原始類型擴展方法

用法四  索引器(基於索引器封裝EPList,用於優化大數據下頻發的Linq查詢引起的程序性能問題,經過索引從list集合中查詢數據

相關文章
相關標籤/搜索