본문 바로가기
언어 정리/C# 개념 및 lib

생성자

by 알 수 없는 사용자 2024. 1. 9.

 

 


 

인자의 갯수와 자료형에 따라 대응하는 생성자

템플릿 + 오버로딩 생성자(overloaded constructor) 사용

코드

using System;

public class Test<T_1, T_2>
{
    public T_1 First { get; set; }
    public T_2 Second { get; set; }

    // 인자로 하나만 오는 경우
    public Test(T_1 first)
    {
        this.First = first;
        this.Second = default(T_2);
    }

    // 인자로 두 개가 오는 경우
    public Test(T_1 first, T_2 second)
    {
        this.First = first;
        this.Second = second;
    }
}

class Program
{
    static void Main()
    {
        Test<int, string> test1 = new Test<int, string>(1); // First = 1, Second = null
        Test<string, int> test2 = new Test<string, int>("Hello"); // First = "Hello", Second = 0
        Test<string, int> test3 = new Test<string, int>("Hello", 1); // First = "Hello", Second = 1

        // 이하 결과 출력 등 추가 작업을 할 수 있습니다.
        Console.WriteLine($"test1: First = {test1.First}, Second = {test1.Second ?? "null"}");
        Console.WriteLine($"test2: First = {test2.First}, Second = {test2.Second}");
        Console.WriteLine($"test3: First = {test3.First}, Second = {test3.Second}");
    }
}

오버로딩 생성자(overloaded constructor)

 

 

출력 :

 

 

 

 

 

 

 

 

 

댓글