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# 구문 및 사용의 최종 소스입니다.
참고하십시오
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET