this(C# 参考)this (C# Reference)

this 关键字指代类的当前实例,还可用作扩展方法的第一个参数的修饰符。The this keyword refers to the current instance of the class and is also used as a modifier of the first parameter of an extension method.

备注

本文介绍 this 在类实例中的用法。This article discusses the use of this with class instances. 若要深入了解它在扩展方法中的用法,请参阅扩展方法For more information about its use in extension methods, see Extension Methods.

以下是 this 的常见用法:The following are common uses of this:

  • 限定类似名称隐藏的成员,例如:To qualify members hidden by similar names, for example:
public class Employee
{
    private string alias;
    private string name;

    public Employee(string name, string alias)
    {
        // Use this to qualify the members of the class 
        // instead of the constructor parameters.
        this.name = name;
        this.alias = alias;
    }
}
  • 将对象作为参数传递给方法,例如:To pass an object as a parameter to other methods, for example:

    CalcTax(this);  
    
  • 声明索引器,例如:To declare indexers, for example:

public int this[int param]
{
    get { return array[param]; }
    set { array[param] = value; }
}

静态成员函数,因为它们存在于类级别且不属于对象,不具有 this 指针。Static member functions, because they exist at the class level and not as part of an object, do not have a this pointer. 在静态方法中引用 this 是错误的。It is an error to refer to this in a static method.

示例Example

在此示例中,this 用于限定类似名称隐藏的 Employee 类成员、namealiasIn this example, this is used to qualify the Employee class members, name and alias, which are hidden by similar names. 它还用于将某个对象传递给属于其他类的方法 CalcTaxIt is also used to pass an object to the method CalcTax, which belongs to 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
 */

C# 语言规范C# Language Specification

有关详细信息,请参阅 C# 语言规范For more information, see the C# Language Specification. 该语言规范是 C# 语法和用法的权威资料。The language specification is the definitive source for C# syntax and usage.

请参阅See Also