this(C# 참조)

this 키워드는 클래스의 현재 인스턴스를 참조합니다.

일반적으로 this 키워드는 다음과 같이 사용됩니다.

  • 예를 들어, 비슷한 이름으로 숨겨진 멤버를 지정하는 방법은 다음과 같습니다.

    public Employee(string name, string alias) 
    {
        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 클래스 멤버(name, alias)를 한정하는 데 사용됩니다. 또한 다른 클래스에 속한 CalcTax 메서드로 개체를 전달하는 데 사용됩니다.

// keywords_this.cs
// this example
using System;
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("John M. Trainer", "jtrainer");

        // Display results:
        E1.printEmployee();
    }
}

출력

Name: John M. Trainer
Alias: jtrainer
Taxes: $240.00

다른 예제를 보려면 classstruct를 참조하십시오.

C# 언어 사양

자세한 내용은 C# 언어 사양의 다음 단원을 참조하십시오.

  • 7.5.7 this 액세스

  • 10.2.6.4 this 액세스

참고 항목

참조

C# 키워드
base(C# 참조)
메서드(C# 프로그래밍 가이드)

개념

C# 프로그래밍 가이드

기타 리소스

C# 참조