C#/클래스와 객체지향

C# 클래스와 객체지향 - 18. 제네릭

tita 2024. 5. 29. 18:04

[제네릭]

List<int> list = new List<int>();

 

List클래스의 꺾은 괄호 사용하는 이러한 것을 제네릭(Generic)이라 부릅니다. 제네릭은 클래스 내부에서 자료형에 별칭을 지정하는 기능입니다. 

제네릭을 활용하는 클래스를 구현할 때는 다음과 같이, 클래스를 선언할 때 뒤에 <> 기호를 사용해줍니다.

class Wanted<T>
{

}

 

위의 코드에서는 T라는 식별자를 사용했습니다. 이렇게 <> 기호 내부에 식별자를 지정해서 Wanted<int>처럼 사용하면 T에 int 자료형이 할당됩니다. 

 

class Wanted<T>
{
    public T value;
    public Wanted(T value)
    {
    	this.Value = value;
    }
}


class Program
{
	static void Main(string[] args)
    {
    	Wanted<string> wantedString = new Wanted<string>("String");
        Wanted<int> wantedInt = new Wanted<int>("Int");
        Wanted<double> wantedDouble = new Wanted<double>("Double");
        
        Console.WriteLine(wantedString.Value);
        Console.WriteLine(wantedInt.Value);
        Console.WriteLine(wantedDouble.Value);
    }
}

/*
[실행 결과]
String
52273
52.273
*/

 

제네릭을 두 개 이상 지정할 수 있습니다.

class Test<T, U>
{

}

 

제네릭을 사용할 때 주의할 점이 있습니다.

제네릭에 모든 자료형을 허용하면 안되는 경우가 있는데, 이럴 때는 where 키워드를 사용해서 제네릭을 제한합니다.

class Test<T, U>
{
    Where T : class // T는 클래스여야 합니다.
    Where U : struct { } // U는 구조체여야 합니다.
}