C#學習系列-this的使用

來源:互聯網
上載者:User

標籤:style   blog   http   color   使用   strong   ar   2014   

如有錯誤,歡迎指正。

1.代表當前類,在當前類中可使用this訪問當前類成員變數和方法(需要注意的是 靜態方法中不能使用this),也可用於參數傳遞,傳遞當前對象的引用。

下面貼代碼:

    class Program    {        static void Main(string[] args)        {            thisClass testObj = new thisClass();            Console.ReadLine();        }    }    class thisClass    {        private string A { get; set; }        public thisClass()        {            /*當前類this 訪問類中屬性A 靜態方法無法訪問A屬性*/            this.A = "Test String";            Console.WriteLine(this.TestFun("TestFun :"));        }        private string TestFun(string args)        {            return args + this.A;        }    }

2.聲明索引器

索引器:允許類和結構的執行個體按照與數組相同的方式進行索引,索引器類似與屬性,不同之處在於他們的訪問器採用參數,被稱為有參屬性,索引可以被重載,屬於執行個體成員,不能聲明為static。

下面貼代碼:

    class Program    {        static void Main(string[] args)        {            indexClass intIndexClass = new indexClass();            intIndexClass[0] = new thisClass("intIndexClass 111");            intIndexClass[1] = new thisClass("intIndexClass 222");            indexClass stringIndexClass = new indexClass();            stringIndexClass["string1"] = new thisClass("stringIndexClass string1");            stringIndexClass["string2"] = new thisClass("stringIndexClass string2");            Console.ReadLine();        }    }    class indexClass    {        /*聲明屬性*/        private thisClass[] thisClassArr = new thisClass[10];        private Hashtable thisClassStrArr = new Hashtable();        /*建立索引器1 索引可以被重載,屬於執行個體成員,不能聲明為static*/        public  thisClass this[int index]        {            get { return thisClassArr[index]; }            set { this.thisClassArr[index] = value; }        }        /*建立索引器2*/        public thisClass this[string index]        {            get            {                return thisClassStrArr[index] as thisClass;            }            set { this.thisClassStrArr[index] = value; }        }    }    class thisClass    {        private string A { get; set; }        public thisClass(string str)        {            /*當前類this 訪問類中屬性A 靜態方法無法訪問A屬性*/            this.A = str;            Console.WriteLine(this.TestFun("TestFun :"));        }        private string TestFun(string args)        {            return args + this.A;        }    }

 我看了好像就這麼多,其他還有補充的沒?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.