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集合中查詢數據


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM