푸터 콘텐츠로 바로가기
.NET 도움말

C# This (개발자를 위한 작동 방식)

C#에서 특별한 중요성을 지닌 특정 키워드가 있습니다. 그것이 바로 this 키워드입니다. 이 키워드는 사용된 현재 클래스 인스턴스를 참조합니다. 동일한 이름을 공유하는 클래스 수준 변수와 메서드 매개변수를 구별하는 데 사용할 수 있습니다. 예를 들어, 같은 이름의 인스턴스 변수와 메소드 매개변수를 가지고 있을 때, this가 매우 유용할 수 있습니다!

this 키워드의 기본 사항

예를 들어 Employee 같은 공개 클래스에서 id 또는 name 같은 공개 인스턴스 변수를 가질 수 있습니다. 메서드 내에서 이러한 인스턴스 변수에 값을 할당하려고 할 때, 메서드 인자가 인스턴스 변수와 동일한 이름을 가질 경우 흔히 발생하는 문제에 부딪힐 수 있습니다.

해결책: C# 문서의 this 키워드를 사용하세요! 공개 클래스 Employee 내부에 있는 메소드의 예에서, this 키워드는 같은 이름을 공유하는 인스턴스 변수와 메소드 매개변수를 구분하는 데 사용됩니다.

public class Employee
{
    private int id;
    private string name;

    public void Display(int id, string name)
    {
        // Use `this.id` to refer to the instance variable, 
        // and `id` for the method parameter.
        this.id = id;
        this.name = name;
    }
}
public class Employee
{
    private int id;
    private string name;

    public void Display(int id, string name)
    {
        // Use `this.id` to refer to the instance variable, 
        // and `id` for the method parameter.
        this.id = id;
        this.name = name;
    }
}
Public Class Employee
	Private id As Integer
	Private name As String

	Public Sub Display(ByVal id As Integer, ByVal name As String)
		' Use `this.id` to refer to the instance variable, 
		' and `id` for the method parameter.
		Me.id = id
		Me.name = name
	End Sub
End Class
$vbLabelText   $csharpLabel

이 경우 this.id는 인스턴스 변수를 가리키고, id는 메소드 매개변수입니다.

생성자 오버로딩에서의 this 키워드

this 키워드를 활용하면, 같은 클래스 내에서 생성자 오버로딩이 강력한 기법이 됩니다. 클래스가 여러 개의 매개변수가 있는 생성자를 포함하는 경우, 예를 들어 Student 클래스에서는 this 키워드를 사용하여 하나의 생성자가 다른 생성자를 호출할 수 있어 중복 코드의 필요성을 없앨 수 있습니다.

매개변수가 있는 생성자에서 this가 사용된 다음의 예를 고려해보세요:

public class Student
{
    private string name;
    private int id;

    public Student() : this("Default", 0)
    {
        // Default constructor delegates to the parameterized constructor
        // with "Default" as the name and 0 as the id.
    }

    public Student(string name, int id)
    {
        // Assign the parameters to the instance variables
        this.name = name;
        this.id = id;
    }
}
public class Student
{
    private string name;
    private int id;

    public Student() : this("Default", 0)
    {
        // Default constructor delegates to the parameterized constructor
        // with "Default" as the name and 0 as the id.
    }

    public Student(string name, int id)
    {
        // Assign the parameters to the instance variables
        this.name = name;
        this.id = id;
    }
}
Public Class Student
	Private name As String
	Private id As Integer

	Public Sub New()
		Me.New("Default", 0)
		' Default constructor delegates to the parameterized constructor
		' with "Default" as the name and 0 as the id.
	End Sub

	Public Sub New(ByVal name As String, ByVal id As Integer)
		' Assign the parameters to the instance variables
		Me.name = name
		Me.id = id
	End Sub
End Class
$vbLabelText   $csharpLabel

매개변수가 없는 생성자에서 this("Default", 0)가 매개변수가 있는 생성자를 호출하고, Default를 이름으로 설정하고 0를 ID로 설정합니다.

확장 메소드에서 this 탐색하기

C#의 확장 메서드는 기존 타입을 수정하지 않고 메서드를 추가하는 방법을 제공합니다. 여기서 this 키워드가 마법 같은 기능을 수행합니다. 확장 메서드의 매개변수 목록에서 확장되는 타입을 참조하기 위해 사용됩니다.

다음은 확장 메서드의 예제입니다.

public static class StringExtensions
{
    // This extension method can be called on any string instance
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}
public static class StringExtensions
{
    // This extension method can be called on any string instance
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }
}
Public Module StringExtensions
	' This extension method can be called on any string instance
	<System.Runtime.CompilerServices.Extension> _
	Public Function IsNullOrEmpty(ByVal str As String) As Boolean
		Return String.IsNullOrEmpty(str)
	End Function
End Module
$vbLabelText   $csharpLabel

여기서 this string str가 이 문자열 타입에 대한 확장 메소드임을 C#에 알립니다. 이제 if(myString.IsNullOrEmpty()) 같은 모든 문자열 객체에서 이 메소드를 사용할 수 있습니다.

인덱서에서의 this

this 키워드는 인덱서를 정의할 때도 사용할 수 있습니다. 인덱서는 배열처럼 클래스 인스턴스를 인덱스화할 수 있게 합니다. 이를 통해 인덱스와 같은 표기법으로 객체 내 데이터를 접근할 수 있습니다. 인덱서에서, this는 보통 int index인 배열 인덱스를 따릅니다.

다음은 인덱서의 기본적인 예제입니다.

public class Test
{
    private int[] array = new int[100];

    // Define an indexer for the class
    public int this[int index]
    {
        get { return array[index]; }
        set { array[index] = value; }
    }
}
public class Test
{
    private int[] array = new int[100];

    // Define an indexer for the class
    public int this[int index]
    {
        get { return array[index]; }
        set { array[index] = value; }
    }
}
Public Class Test
	Private array(99) As Integer

	' Define an indexer for the class
	Default Public Property Item(ByVal index As Integer) As Integer
		Get
			Return array(index)
		End Get
		Set(ByVal value As Integer)
			array(index) = value
		End Set
	End Property
End Class
$vbLabelText   $csharpLabel

이 클래스 Test에서, this 키워드는 array 인스턴스 필드에서 값을 가져오거나 설정할 수 있는 인덱서를 정의합니다.

this 및 정적 멤버

this에 대해 주의할 점은 정적 멤버나 메소드를 참조하는 데 사용할 수 없다는 것입니다. 이는 this가 현재 인스턴스를 참조하고, 정적 멤버는 클래스 자체에 속하며 클래스의 인스턴스에 속하지 않기 때문입니다.

public class Program
{
    public static void Main(string[] args)
    {
        // Can't use `this` here, because 'Main' is a static method.
    }
}
public class Program
{
    public static void Main(string[] args)
    {
        // Can't use `this` here, because 'Main' is a static method.
    }
}
Public Class Program
	Public Shared Sub Main(ByVal args() As String)
		' Can't use `this` here, because 'Main' is a static method.
	End Sub
End Class
$vbLabelText   $csharpLabel

그러니 기억하세요, this는 인스턴스를 위한 것이고 클래스 수준이나 정적 멤버를 위한 것이 아닙니다!

this 키워드 및 속성

인스턴스 변수와 메소드 매개변수처럼, this 키워드는 속성과 함께 사용할 수도 있습니다. C#에서 속성은 개인 필드의 값을 읽거나 쓰거나 계산하는 유연한 메커니즘을 제공하는 멤버입니다. 속성은 공개 데이터 멤버처럼 사용할 수 있지만, 실제로는 접근자라는 특별한 메서드입니다.

this를 속성에서 사용하는 간단한 예를 살펴보겠습니다.

public class Employee
{
    private string name;

    public string Name
    {
        get { return this.name; }
        set { this.name = value; } // Use `this` to refer to the instance variable
    }
}
public class Employee
{
    private string name;

    public string Name
    {
        get { return this.name; }
        set { this.name = value; } // Use `this` to refer to the instance variable
    }
}
Public Class Employee
'INSTANT VB NOTE: The field name was renamed since Visual Basic does not allow fields to have the same name as other class members:
	Private name_Conflict As String

	Public Property Name() As String
		Get
			Return Me.name_Conflict
		End Get
		Set(ByVal value As String)
			Me.name_Conflict = value
		End Set ' Use `this` to refer to the instance variable
	End Property
End Class
$vbLabelText   $csharpLabel

위의 클래스에서 this 키워드는 name라는 비공개 문자열을 Name 속성의 get 및 set 접근자에서 참조하는 데 사용됩니다.

this 및 대리자 탐색하기

this가 나타나는 또 다른 곳은 대리자입니다. C#에서 대리자는 C나 C++의 함수 포인터와 유사합니다. 이는 메서드에 대한 참조를 보유하는 참조형 변수입니다. 확장 메소드처럼 대리자 메소드도 this를 사용하여 현재 인스턴스에 접근할 수 있습니다.

this을 사용하는 대리자의 예입니다:

public delegate void DisplayDelegate();

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public void Display()
    {
        // `this.DisplayDetails` refers to the method instance of the current object.
        DisplayDelegate displayDelegate = new DisplayDelegate(this.DisplayDetails);
        displayDelegate();
    }

    private void DisplayDetails()
    {
        Console.WriteLine("ID: " + Id + ", Name: " + Name);
    }
}
public delegate void DisplayDelegate();

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }

    public void Display()
    {
        // `this.DisplayDetails` refers to the method instance of the current object.
        DisplayDelegate displayDelegate = new DisplayDelegate(this.DisplayDetails);
        displayDelegate();
    }

    private void DisplayDetails()
    {
        Console.WriteLine("ID: " + Id + ", Name: " + Name);
    }
}
Public Delegate Sub DisplayDelegate()

Public Class Student
	Public Property Id() As Integer
	Public Property Name() As String

	Public Sub Display()
		' `this.DisplayDetails` refers to the method instance of the current object.
		Dim displayDelegate As New DisplayDelegate(AddressOf Me.DisplayDetails)
		displayDelegate()
	End Sub

	Private Sub DisplayDetails()
		Console.WriteLine("ID: " & Id & ", Name: " & Name)
	End Sub
End Class
$vbLabelText   $csharpLabel

학생 클래스에서, this.DisplayDetails 가 현재 객체의 DisplayDetails 메소드를 참조하는 새로운 대리자 인스턴스를 만듭니다.

IronPDF와 함께 this 키워드 구현하기

강력한 .NET 라이브러리인 IronPDF와 함께 this 키워드를 사용할 수 있는 예를 살펴보겠습니다. 이 라이브러리는 HTML을 사용하여 PDF 파일을 편집 및 생성하는 것입니다.

IronPDF 라이브러리를 사용하여 PDF 파일에서 다양한 작업을 수행하는 PDFHandler라는 클래스 예시를 고려해보세요:

using IronPdf;

public class PDFHandler
{
    private string path;

    public PDFHandler(string path)
    {
        this.path = path;
    }

    public void GeneratePDF(string content)
    {
        // Creating a renderer to convert HTML content to PDF
        var Renderer = new IronPdf.ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(content);

        // Save the generated PDF to the path specified by the current instance
        PDF.SaveAs(this.path);
    }
}
using IronPdf;

public class PDFHandler
{
    private string path;

    public PDFHandler(string path)
    {
        this.path = path;
    }

    public void GeneratePDF(string content)
    {
        // Creating a renderer to convert HTML content to PDF
        var Renderer = new IronPdf.ChromePdfRenderer();
        var PDF = Renderer.RenderHtmlAsPdf(content);

        // Save the generated PDF to the path specified by the current instance
        PDF.SaveAs(this.path);
    }
}
Imports IronPdf

Public Class PDFHandler
	Private path As String

	Public Sub New(ByVal path As String)
		Me.path = path
	End Sub

	Public Sub GeneratePDF(ByVal content As String)
		' Creating a renderer to convert HTML content to PDF
		Dim Renderer = New IronPdf.ChromePdfRenderer()
		Dim PDF = Renderer.RenderHtmlAsPdf(content)

		' Save the generated PDF to the path specified by the current instance
		PDF.SaveAs(Me.path)
	End Sub
End Class
$vbLabelText   $csharpLabel

PDFHandler 클래스에서는 this 키워드가 현재 인스턴스의 path 필드를 참조하는 데 사용됩니다. 이 필드는 생성된 PDF를 지정된 경로에 저장하는 데 사용됩니다.

우리가 PDFHandler의 새 인스턴스를 만들고 GeneratePDF 메소드를 호출하면, this 키워드는 객체 생성 시 지정된 path를 활용할 수 있게 해줍니다:

class Program
{
    static void Main(string[] args)
    {
        // Initialize PDFHandler with a specified file path
        PDFHandler pdfHandler = new PDFHandler("C:\\ThisKeyword.pdf");
        pdfHandler.GeneratePDF("Hello World!");
    }
}
class Program
{
    static void Main(string[] args)
    {
        // Initialize PDFHandler with a specified file path
        PDFHandler pdfHandler = new PDFHandler("C:\\ThisKeyword.pdf");
        pdfHandler.GeneratePDF("Hello World!");
    }
}
Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Initialize PDFHandler with a specified file path
		Dim pdfHandler As New PDFHandler("C:\ThisKeyword.pdf")
		pdfHandler.GeneratePDF("Hello World!")
	End Sub
End Class
$vbLabelText   $csharpLabel

여기서 this는 특히 IronPDF 같은 라이브러리를 다룰 때 코드를 더 읽기 쉽고 이해하기 쉽게 만듭니다.

C# This (개발자를 위한 작동 방식) 1번 그림

결론

이제 this 키워드에 대해 잘 이해했을 것입니다. 여기에는 간단한 인스턴스 변수부터 생성자, 확장 메소드, 속성, 대리자, 익명 메소드 및 IronPDF 같은 인기 있는 라이브러리를 사용할 때까지 다양한 사용 사례가 포함됩니다.

IronPDF는 IronPDF 무료 체험판을 제공하므로 오늘 배운 모든 것들을 시험해볼 수 있습니다. 계속 사용하기로 결정하셨다면, 라이센스는 단 $liteLicense부터 시작합니다. IronPDF는 C# 개발 도구 모음에 있어 값진 추가 기능이 될 수 있으며, 앱에서 PDF 파일을 처리하는 작업을 단순화할 수 있습니다.

자주 묻는 질문

'this' 키워드가 C#에서 클래스 변수와 메서드 매개변수를 어떻게 구분할 수 있습니까?

C#에서 'this' 키워드는 현재 클래스 인스턴스를 가리키는 데 사용되며, 같은 이름을 공유하는 클래스 레벨 변수와 메서드 매개변수를 구분할 수 있게 해줍니다. 이는 메서드 내에서의 이름 충돌을 피하는 데 특히 유용합니다.

생성자 오버로딩에서 'this'의 중요성은 무엇인가요?

생성자 오버로딩에서 'this'는 같은 클래스 내에서 한 생성자가 다른 생성자를 호출할 수 있게 해줍니다. 이는 기존의 생성자 로직을 재사용함으로써 중복 코드를 줄이고 일관성과 유지보수성을 보장하는 데 도움이 됩니다.

'this'는 C#에서 확장 메서드 사용을 어떻게 촉진하나요?

'this' 키워드는 확장 메서드의 매개변수 목록에서 확장되는 타입을 나타내기 위해 사용됩니다. 이를 통해 개발자는 소스 코드를 수정하지 않고 기존 타입에 새로운 메서드를 추가할 수 있어 기능을 매끄럽게 확장할 수 있습니다.

'this'는 인덱서와 어떤 방식으로 사용되나요?

C#에서 'this'는 인덱서와 함께 사용되어 배열과 같은 표기법으로 클래스 인스턴스를 접근할 수 있게 하는 속성을 정의합니다. 이는 개체 내 데이터 접근의 가독성과 사용성을 향상시킵니다.

왜 'this'를 C#의 정적 멤버에 사용할 수 없나요?

'this' 키워드는 클래스의 인스턴스 멤버를 참조하는 것이며, 정적 멤버는 특정 인스턴스가 아닌 클래스 자체에 속합니다. 따라서 'this'는 정적 멤버나 메서드를 참조하는 데 사용할 수 없습니다.

'this' 키워드는 C# 클래스의 속성 접근을 어떻게 향상시키나요?

'this' 키워드는 속성의 get 및 set 접근자 내에서 현재 클래스 인스턴스의 비공개 필드를 참조하는 데 사용될 수 있습니다. 이는 클래스 자신의 필드에 대한 작업임을 명시적으로 나타내어 코드의 명확성을 높입니다.

대리자 맥락에서 'this'는 어떤 역할을 하나요?

대리자 맥락에서 'this'는 대리자가 현재 개체의 메서드 인스턴스를 참조할 수 있게 해줍니다. 이는 대리자를 통한 인스턴스 메서드 호출에 중요하며, 이벤트 처리를 유연하게 하고 콜백을 제공합니다.

IronPDF 라이브러리를 사용할 때 'this'가 코드 가독성을 어떻게 향상시킬 수 있나요?

IronPDF 라이브러리를 사용할 때, 'this'는 파일 경로와 같은 인스턴스 변수를 명확히 하여 코드의 가독성을 높일 수 있습니다. 특히 PDF 파일을 생성하고 저장하는 작업 시 코드의 명확성과 유지 관리성을 높이는 데 유용합니다.

제이콥 멜러, 팀 아이언 최고기술책임자
최고기술책임자

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.

제이콥은 맨체스터 대학교에서 토목공학 학사 학위(BEng)를 최우등으로 취득했습니다(1998~2001). 1999년 런던에서 첫 소프트웨어 회사를 설립하고 2005년 첫 .NET 컴포넌트를 개발한 후, 마이크로소프트 생태계 전반에 걸쳐 복잡한 문제를 해결하는 데 전문성을 발휘해 왔습니다.

그의 대표 제품인 IronPDF 및 Iron Suite .NET 라이브러리는 전 세계적으로 3천만 건 이상의 NuGet 설치 수를 기록했으며, 그의 핵심 코드는 전 세계 개발자들이 사용하는 다양한 도구에 지속적으로 활용되고 있습니다. 25년의 실무 경험과 41년의 코딩 전문성을 바탕으로, 제이콥은 차세대 기술 리더들을 양성하는 동시에 기업 수준의 C#, Java, Python PDF 기술 혁신을 주도하는 데 주력하고 있습니다.

아이언 서포트 팀

저희는 주 5일, 24시간 온라인으로 운영합니다.
채팅
이메일
전화해