Original address: Https://msdn.microsoft.com/zh-cn/library/dk1507sz.aspx
The This keyword refers to the current instance of a class and can also be used as the modifier for the first parameter of an extension method.
| Attention |
This article discusses the use of this for class instances. For more information about its use in extension methods, see extension Methods (C # Programming Guide). |
The following are the common uses of this:
C#
Public Employee (string name, string alias) { //Use the-qualify the fields, name and alias: this.name = name;
this.alias = alias;}
Pass the object as a parameter to another method, for example:
Calctax (this);
Declare indexers, for example:
C#
public int This[int param]{ get {return array[param];} set {Array[param] = value;}}
Because a static member function exists at the class level and is not part of an object, There is no this pointer. It is an error to refer to this in a static method.
Example
In this case, this is used to qualify the Employee class member name and alias, which are hidden by similar names. The keyword is also used to pass an object to a method calctax that belongs to another class .
C#
Class employee{ private string name; private string alias; Private decimal salary = 3000.00m; Constructor: Public Employee (string name, string alias) { //qualify-the fields, name and alias : this.name = name; This.alias = alias; } Printing method: Public void Printemployee () { Console.WriteLine ("Name: {0}\nalias: {1}", Name, alias); Passing the object to the Calctax method by using this: Console.WriteLine ("Taxes: {0:c}", Tax.calctax (This));
} public decimal Salary { get {return Salary;}} } Class tax{public static decimal calctax (Employee E) { return 0.08m * e.salary; }} Class mainclass{ static void Main () { //Create objects: Employee E1 = new Employee ("Mingda Pan", "MP An "); Display results: e1.printemployee (); }} /*output: name:mingda Pan alias:mpan Taxes: $240.00 * *
This (C # Reference)