C # reference "This"

Source: Internet
Author: User
This is a reserved word in C #. It allows an object to point to itself. Inside the method, this reference can be used to point to any currently executed object.
For example, in a class called chesspiece, a method called move may contain the following rows:
If (this. Position = piece. position)
Result = false;
In this case, this reference is used to clarify which position is referenced. This references the object that points to the trigger method. So if the following line uses
In the trigger method, this references to firstshop:
Firstshop. Move ();
However, if another object is used to trigger a method, this reference points to it. Therefore, if the following call is used, this reference in the move Method
Point to secondshop:
Secondshop. Move ();
Often, this reference is used to distinguish between constructors and their corresponding instance variables with the same name. For example, a constructor called the account class
As follows:

Public Account ( String Owner, Long Account, Double Initial)
{
Name=Owner;
Acctnumber=Account;
Balance=Initial;
}

When writing this constructor, we specifically set different names for parameters to distinguish them from the instance variable name, accnumber, and balance. This distinction is arbitrary. The constructor can use this reference as follows: (this is easier to understand and accept)

Public Account ( String Name, Long Acctnumber, Double Balance)
{
This. Name=Name;
This. Acctnumber=Acctnumber;
This. Balance=Balance;
}

In this version of Constructor (non-static constructor is automatically called when class objects are created), This references instance variables that specifically point to objects. The variable on the right of the value assignment statement points to the form parameter. This method eliminates the need to get different but equivalent names for variables. This happens in other methods, but usually in constructors.

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.