This keyword, javathis keyword
This is a reserved word and is only used by constructors and method members;
In the constructor of a class, it indicates reference to the object itself being constructed, and in the class method, it indicates reference to the object that calls this method, in the structure constructor, the function indicates a reference to the structure being constructed. In the structure method, it indicates a reference to the result of calling this method;
This reserved word cannot be used in the implementation of static members, because the object or structure is not instantiated;
In the C # system, this is actually a constant, so this ++ cannot be used;
This reserved word is generally used to restrict hidden members with the same name, use the object as a parameter, declare the index accessor, and determine whether the object of the input parameter is itself.
Usage 1: Restrict hidden members with similar names
public Employee(string name, string alias) { // Use this to qualify the fields, name and alias: this.name = name; this.alias = alias; }
Usage 2: passing objects as parameters to other methods
CalcTax(this);
Usage 3: declare the Indexer
public int this[int param] { get { return array[param]; } set { array[param] = value; } }
Example:
class Employee { private string name; private string alias; private decimal salary = 3000.00m; // Constructor: public Employee(string name, string alias) { // Use this to 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", "mpan"); // Display results: E1.printEmployee(); } }
/*
Output:
Name: Mingda Pan
Alias: mpan
Taxes: $240.00
*/