C#this的五種用法

來源:互聯網
上載者:User

標籤:

this的五種用法:

1.使用被掩蓋的成員變數:

class AA

{

        int a;

        public void set1(int a)

        {

            this.a = a;//right

        }

        public void set2(int a)

        {

            a = a;//會有警告:“對同一變數進行賦值;是否希望對其他變數賦值?”;

        }

}

2.把這個對象傳給其他函數

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{    class BB    {        static public void set(AA t,int a)        {            t.set1(a);        }    }    class AA    {        int a;        public void set1(int a)        {            this.a = a;        }        public void set2(int a)        {            BB.set(this, a);        }        public int get()        {            return a;        }    }        class Program    {        static void Main(string[] args)        {            AA t = new AA();            t.set2(123);            Console.WriteLine(t.get());        }    }}

 

3.With Indexers(索引器)//這個暫時不懂

4.調用其他建構函式

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{    class AA    {        int a, b;        public AA(int a)        {            this.a = a;            b = -1;            print();        }        public AA(int a,int b):this(a)        {            this.b = b;            print();        }        void print()        {            Console.WriteLine("{0} {1}", a, b);        }    }    class Program    {        static void Main(string[] args)        {            AA t = new AA(1);            t = new AA(1, 1);        }    }}

輸出:

1 -1

1 -1

1 1

5.是代碼更明確

如把

        public AA(int a)        {            this.a = a;            b = -1;            print();        }    

改為

        public AA(int a)        {            this.a = a;            this.b = -1;            print();        }

 

C#this的五種用法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.