The C # thisthis keyword references the current instance of the class and can also be used as the modifier of the first parameter of the extension method.
The following are common uses of this:
Restrict hidden members by similar names. For example: (the name field has been declared and defined in the class where the Empioyee method is located)
public Employee(string name, string alias){ // Use this to qualify the fields, name and alias: this.name = name; this.alias = alias;}
Passing objects as parameters to other methods, such:
CalcTax (this );
Declare the indexer, for example:
Public int this [int param]
{
Get {return array [param];}
Set {array [param] = value ;}
}
Because static member functions exist at the class level and are not part of an object, there is no this pointer. It is wrong to reference this in a static method. In this example, this is used to limit the names and alias of the members of the Employee class, which are hidden by similar names. This is also used to pass an object to the CalcTax method of another class.
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 */
In addition, in the C/S structure application, you can use this to pass the window object // <summary>
/// Click the close button
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Private void tsMain_Close_Click (object sender, EventArgs e)
{
// The method for closing the page is to close the Instance Object of the page. The keyword "this" is the object of the current page.
This. Close ();
}