this(C# 참조)

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

참고 항목

이 문서에서는 클래스 인스턴스와 함께 this를 사용하는 방법을 설명합니다. 확장 메서드에서 사용하는 방법에 대한 자세한 내용은 확장 메서드를 참조하세요.

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 { return array[param]; }
        set { array[param] = value; }
    }
    

정적 멤버 함수는 개체의 일부가 아니라 클래스 수준에 있기 때문에 this 포인터가 없습니다. 정적 메서드에서 this를 참조하면 오류가 발생합니다.

예시

이 예제에서는 this를 사용하여 유사한 이름으로 숨겨진 Employee 클래스 멤버 namealias를 한정합니다. 다른 클래스에 속하는 CalcTax 메서드에 개체를 전달하는 데에도 사용됩니다.

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# 언어 사양을 참조하세요. 언어 사양은 C# 구문 및 사용법에 대 한 신뢰할 수 있는 소스 됩니다.

참고 항목