HOWTO · Csharp
C#의 다른 생성자에서 생성자 호출
this 키워드는 C#에서 동일한 클래스의 다른 생성자에서 하나의 생성자를 호출하는 데 사용할 수 있습니다.
이 페이지의 내용
이 자습서에서는 C#에서 동일한 클래스의 다른 생성자에서 하나의 생성자를 호출하는 메서드에 대해 설명합니다.
C#에서this키워드를 사용하여 동일한 클래스의 다른 생성자에서 하나의 생성자 호출
클래스에 여러 생성자가 있고 다른 생성자에서 하나의 생성자를 호출하려면 C#에서this키워드를 사용할 수 있습니다. this키워드는 C#에서 현재 클래스의 인스턴스에 대한 참조입니다. 다음 코드 예제는 C#에서this키워드를 사용하여 동일한 클래스의 다른 생성자에서 클래스의 한 생성자를 호출하는 방법을 보여줍니다.
using System;
namespace call_another_constructor {
class sample {
public sample() {
Console.WriteLine("Constructor 1");
}
public sample(int x) : this() {
Console.WriteLine("Constructor 2, value: {0}", x);
}
public sample(int x, int y) : this(x) {
Console.WriteLine("Constructor 3, value1: {0} value2: {1}", x, y);
}
}
class Program {
static void Main(string[] args) {
sample s1 = new sample(12, 13);
}
}
}
출력:
Constructor 1
Constructor 2, value: 12
Constructor 3, value1: 12 value2: 13
3 개의 다른 생성자로sample클래스를 만들었습니다. 생성자sample(int x, int y)는 생성자sample(int x)를 호출하고this(x)와 함께x를 매개 변수로 전달합니다. 그런 다음sample(int x)생성자가this()를 사용하여sample생성자를 호출합니다. sample생성자는sample(int x)생성자보다 먼저 실행되고sample(int x)생성자는sample(int x, int y)생성자보다 먼저 실행됩니다.