다음을 통해 공유


이 키워드

키워드는 this 클래스의 현재 인스턴스를 참조합니다. 확장 메서드의 첫 번째 매개 변수에 대한 한정자로도 사용됩니다.

비고

이 문서에서는 현재 멤버의 this 수신기 인스턴스를 참조하는 데 사용하는 방법을 설명합니다. 확장 메서드에서 사용하는 방법에 대한 자세한 내용은 키워드를 extension 참조하세요.

C# 언어 참조는 가장 최근에 릴리스된 C# 언어 버전을 문서화합니다. 또한 예정된 언어 릴리스의 공개 미리 보기 기능에 대한 초기 설명서도 포함되어 있습니다.

설명서는 언어의 마지막 세 버전 또는 현재 공개 미리 보기에서 처음 도입된 기능을 식별합니다.

팁 (조언)

C#에서 기능이 처음 도입된 시기를 찾으려면 C# 언어 버전 기록에 대한 문서를 참조하세요.

일반적인 용도는 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 정적 메서드에서 참조하는 것은 오류입니다.

다음 예제에서는 매개 변수 namealias 이름이 같은 필드를 숨깁니다. 키워드는 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# 구문 및 사용의 최종 소스입니다.

참고하십시오