关键字 this 引用类的当前实例,还用作扩展方法的第一个参数的修饰符。
注释
本文讨论如何在类实例中使用this。 有关它在扩展方法中使用的详细信息,请参阅 extension 关键字。
以下是this的常见用法:
- 限定类似名称隐藏的成员,例如: - 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; } }
- 若要将对象作为参数传递给其他方法,例如: - CalcTax(this);
- 声明 索引器,例如: - public int this[int param] { get => array[param]; set => array[param] = value; }
静态成员函数,因为它们存在于类级别,而不是作为对象的一部分存在,因此没有 this 指针。 在静态方法中引用 this 这是一个错误。
在此示例中,参数 name和 alias 隐藏具有相同名称的字段。 关键字 this 将这些变量限定为 Employee 类成员。 关键字 this 还指定属于另一个类的方法 CalcTax的对象。
class Employee
{
    private string name;
    private string alias;
    // 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: {name}
        Alias: {alias}
        """);
        // Passing the object to the CalcTax method by using this:
        Console.WriteLine($"Taxes: {Tax.CalcTax(this):C}");
    }
    public decimal Salary { get; } = 3000.00m;
}
class Tax
{
    public static decimal CalcTax(Employee E)=> 0.08m * E.Salary;
}
class Program
{
    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# 语言规范。 语言规范是 C# 语法和用法的明确来源。