C# this 的用法

轉:https://www.cnblogs.com/yellowcool/p/7908607.html

用法一  this代表當前類的實例對象

    public class Test
    {
        private string scope = "全局變量";
        public string getResult()
        {
            string scope = "局部變量";
       // this代表Test的實例對象
       // 所以this.scope對應的是全局變量
        // scope對應的是getResult方法內的局部變量
            return this.scope + "-" + scope;
        }
    }

 用法二  用this串聯構造函數

public class Test
    {
        public Test()
        {
            Console.WriteLine("無參構造函數");
        }
        // this()對應無參構造方法Test()
     // 先執行Test(),後執行Test(string text)
        public Test(string text) : this()
        {
            Console.WriteLine(text);
            Console.WriteLine("有參構造函數");
        }
    }

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

 擴展後,

string str="tom";

str.isEmail();//多了一個方法

    public static class ExtensionHelper

    {
        //擴展方法必須爲靜態的
        //擴展方法的第一個參數必須由this來修飾(第一個參數是被擴展的對象)
        public static bool isEmail(this string _string)
        {
            return Regex.IsMatch(_string,
                @"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$");


        }
}

 用法四  索引器

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章