this를 사용한 생성자 연결
여러 생성자에서 초기화 코드를 재사용합니다.
this를 사용한 생성자 연결은(는) CoddyKit의 무료 C# Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 C# Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. C# Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
생성자를 연결하는 이유
여러 생성자가 설정 로직을 공유한다면 생성자를 연결하여 한 생성자가 다른 생성자를 호출하게 만들 수 있습니다. 이렇게 하면 코드를 중복하지 않고 초기화 로직을 한곳에 유지할 수 있습니다.
using System;
class Box
{
public int Width;
public int Height;
public Box(int width, int height)
{
Width = width;
Height = height;
}
public Box() : this(1, 1) { }
}
class Program
{
static void Main()
{
var def = new Box();
Console.WriteLine(def.Width + "x" + def.Height);
}
}: this(...) 구문
생성자 시그니처 뒤에 : this(args)를 작성하여 생성자를 연결합니다. 대상 생성자가 먼저 실행된 다음 현재 생성자의 본문이 실행됩니다.
using System;
class Person
{
public string Name;
public int Age;
public Person(string name, int age)
{
Name = name;
Age = age;
Console.WriteLine("Full constructor ran");
}
public Person(string name) : this(name, 0)
{
Console.WriteLine("Name-only constructor ran");
}
}
class Program
{
static void Main()
{
var p = new Person("Sam");
Console.WriteLine(p.Name + ", " + p.Age);
}
}실행 순서
호출하는 생성자의 본문보다 연결된 생성자가 먼저 실행됩니다. 따라서 기본 설정이 항상 먼저 처리됩니다.
using System;
class Step
{
public Step(int n)
{
Console.WriteLine("Init with " + n);
}
public Step() : this(0)
{
Console.WriteLine("Then default body");
}
}
class Program
{
static void Main()
{
var s = new Step();
}
}단일 진실 공급원
모든 생성자를 실제 로직을 담은 하나의 "기본" 생성자로 모으세요. 나머지 생성자는 기본값만 제공하고 해당 생성자에 연결하면 됩니다.
using System;
class Connection
{
public string Host;
public int Port;
public Connection(string host, int port)
{
Host = host;
Port = port;
}
public Connection(string host) : this(host, 8080) { }
public Connection() : this("localhost", 8080) { }
}
class Program
{
static void Main()
{
var c = new Connection("example.com");
Console.WriteLine(c.Host + ":" + c.Port);
}
}기본값을 사용한 연결
생성자 연결은 계층화된 기본값을 명확하게 표현하는 방법입니다. 매개변수가 더 적은 각 생성자가 기본값을 하나씩 채운 뒤 위임합니다.
using System;
class Coffee
{
public string Size;
public bool Milk;
public int Sugar;
public Coffee(string size, bool milk, int sugar)
{
Size = size;
Milk = milk;
Sugar = sugar;
}
public Coffee(string size, bool milk) : this(size, milk, 0) { }
public Coffee(string size) : this(size, false) { }
}
class Program
{
static void Main()
{
var c = new Coffee("large");
Console.WriteLine(c.Size + ", milk=" + c.Milk + ", sugar=" + c.Sugar);
}
}대상 생성자에서의 유효성 검사
모든 생성자가 기본 생성자를 거치므로, 그곳에 작성한 유효성 검사가 모든 생성 경로를 보호합니다.
using System;
class Rect
{
public int W;
public int H;
public Rect(int w, int h)
{
if (w <= 0 || h <= 0)
throw new ArgumentException("Dimensions must be positive");
W = w;
H = h;
}
public Rect(int side) : this(side, side) { }
}
class Program
{
static void Main()
{
var square = new Rect(5);
Console.WriteLine(square.W + "x" + square.H);
}
}생성자 연결과 기본 매개변수 비교
기본 매개변수를 사용하면 여러 오버로드를 대신할 수 있지만, 각 생성자의 본문에 조금씩 다른 로직이 필요하다면 생성자 연결이 더 명확합니다.
using System;
class Logger
{
public string Prefix;
public bool Verbose;
public Logger(string prefix, bool verbose)
{
Prefix = prefix;
Verbose = verbose;
}
public Logger(string prefix) : this(prefix, false)
{
Console.WriteLine("Created quiet logger");
}
}
class Program
{
static void Main()
{
var log = new Logger("APP");
Console.WriteLine(log.Prefix + " verbose=" + log.Verbose);
}
}빈 본문은 흔합니다
생성자를 연결하는 생성자는 모든 작업이 대상 생성자에서 이루어지므로 { } 본문이 비어 있는 경우가 많습니다.
using System;
class Vector
{
public double X, Y, Z;
public Vector(double x, double y, double z)
{
X = x; Y = y; Z = z;
}
public Vector(double v) : this(v, v, v) { }
}
class Program
{
static void Main()
{
var v = new Vector(2);
Console.WriteLine(v.X + "," + v.Y + "," + v.Z);
}
}순환 피하기
생성자를 고리처럼 연결해서는 안 됩니다(A가 B를 호출하고 B가 A를 호출하는 경우). 컴파일러는 순환하는 : this(...) 연결을 거부합니다.
using System;
class Safe
{
public int A, B;
public Safe(int a, int b)
{
A = a;
B = b;
}
public Safe(int a) : this(a, 0) { } // chains one direction only
}
class Program
{
static void Main()
{
var s = new Safe(7);
Console.WriteLine(s.A + ", " + s.B);
}
}this.field와 함께 사용하기
생성자를 연결하면서도 대상 생성자가 반환된 후 본문에서 추가 설정을 위해 this.를 사용할 수 있습니다.
using System;
class Account
{
public string Owner;
public decimal Balance;
public bool Active;
public Account(string owner, decimal balance)
{
this.Owner = owner;
this.Balance = balance;
}
public Account(string owner) : this(owner, 0m)
{
this.Active = true;
}
}
class Program
{
static void Main()
{
var a = new Account("Rin");
Console.WriteLine(a.Owner + " active=" + a.Active);
}
}한데 모아 보기
생성자 연결은 클래스를 DRY하게 유지합니다. 한 생성자가 유효성 검사와 할당을 담당하고, 나머지는 편리한 단축 경로를 제공합니다.
using System;
class Pizza
{
public string Size;
public int Toppings;
public Pizza(string size, int toppings)
{
if (toppings < 0) throw new ArgumentException("toppings");
Size = size;
Toppings = toppings;
}
public Pizza(string size) : this(size, 0) { }
public Pizza() : this("medium") { }
}
class Program
{
static void Main()
{
var p = new Pizza();
Console.WriteLine(p.Size + " with " + p.Toppings + " toppings");
}
}빠른 확인
생성자 연결에 대한 이해도를 확인해 보세요.
복습
생성자 연결은 : this(args)를 사용하여 같은 클래스의 다른 생성자를 호출합니다. 대상 생성자가 먼저 실행되고 현재 생성자의 본문이 그다음에 실행됩니다. 모든 생성자를 하나의 기본 생성자로 연결하면 유효성 검사를 한곳에 모으고 설정 코드 중복을 피할 수 있습니다. 순환 연결은 허용되지 않습니다.
using System;
class Demo
{
public int X, Y;
public Demo(int x, int y) { X = x; Y = y; }
public Demo(int both) : this(both, both) { }
}
class Program
{
static void Main()
{
var d = new Demo(4);
Console.WriteLine(d.X + "," + d.Y);
}
}자주 묻는 질문
“this를 사용한 생성자 연결” 강의는 무료인가요?
네 — “this를 사용한 생성자 연결” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 C# Academy 강의 전체를 잠금 해제할 수 있습니다. C# Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“this를 사용한 생성자 연결”에서 뭘 배우나요?
여러 생성자에서 초기화 코드를 재사용합니다. 브라우저에서 직접 실행하는 실습 코드로 C# Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
C# Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 C# Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“this를 사용한 생성자 연결” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 C# Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 C# Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 생성자 정의
- this를 사용한 생성자 연결
- 객체 및 컬렉션 이니셜라이저
- 정적 생성자