Five Ways to use C#this

Source: Internet
Author: User

Five ways to use this:

1. Use the Masked member variable:

Class AA

{

int A;

public void Set1 (int a)

{

THIS.A = A;//right

}

public void Set2 (int a)

{

A = a;//will have a warning: "Assign a value to the same variable; Do you want to assign a value to another variable?" ;

}

}

2. Pass this object to other functions

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceconsoleapplication1{classBB {Static  Public void Set(AA T,inta) {T.set1 (a); }    }    classAA {intA;  Public voidSet1 (inta) { This. A =A; }         Public voidSet2 (inta) {BB.Set( This, a); }         Public int Get()        {            returnA; }    }        classProgram {Static voidMain (string[] args) {AA T=NewAA (); T.set2 (123); Console.WriteLine (T.Get()); }    }}

3.With Indexers (indexer)//This temporarily does not understand

4. Calling other constructors

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespaceconsoleapplication2{classAA {intA, B;  PublicAA (inta) { This. A =A; b= -1;        Print (); }         PublicAA (intAintb): This(a) { This. B =b;        Print (); }        voidprint () {Console.WriteLine ("{0} {1}", A, b); }    }    classProgram {Static voidMain (string[] args) {AA T=NewAA (1); T=NewAA (1,1); }    }}

Output:

1-1

1-1

1 1

5. Is the code more explicit

such as the

         Public AA (int  a)        {            this. A = A;              =-1;            Print ();        }    

Switch

         Public AA (int  a)        {            this. A = A;              this. B =-1;            Print ();        }

Five Ways to use C#this

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.