제네릭 메서드 (Generic Method)

2022. 1. 26. 00:00CSharp/Advance

반응형

제네릭 메서드는 다음과 같은 형식 매개 변수를 사용하여 선언된 메서드이다.

public void Swap<T>(ref T lhs, ref T rhs)
{
    T temp;
    temp = lhs;
    lhs = rhs;
    rhs = temp;
}
int a = 1;
int b = 2;

Swap<int>(ref a, ref b);
// 형식인수를 생략 할 수도 있다. 
// 컴파일러가 자동으로 유추한다. 
//Swap(ref a, ref b);
System.Console.WriteLine(a + " " + b);

클래스가 제네릭 클래스 라면 다음과 같은 형태로 지정 할 수도 있다. 

// 제네릭 클래스 선언
class SampleClass<T>
{
    // 일반 메소드로 선언하고 클래스의 T type 을 사용한다. 
    void Swap(ref T lhs, ref T rhs) { }
}

메소드 또한 형식 매개변수에 제약 조건을 사용 가능 하다. 

void SwapIfGreater<T>(ref T lhs, ref T rhs) where T : System.IComparable<T>
{
    T temp;
    if (lhs.CompareTo(rhs) > 0)
    {
        temp = lhs;
        lhs = rhs;
        rhs = temp;
    }
}

아래와 같은 일반 method 호출은 generic method 형태로 변경할 수 있다.

일반 메소드

private void Print(List<Shape> list)
{
    foreach (var item in list) item.PrintDraw();
}

Generic Method

// generic method 로 print 변경
private void Print<T>(IList<T> list) where T : Shape
{
    foreach (var item in list) item.PrintDraw();
}

컴파일러의 타입 유추에 의해 Print() 형태로 똑같이 사용하게 된다. 

 

 

 

관련영상

https://youtu.be/xUYG89wtlr8

 

 

반응형

'CSharp > Advance' 카테고리의 다른 글

제네릭 리플렉션 (Generic Reflection)  (0) 2022.01.28
제네릭 대리자 (Generic Delegate)  (0) 2022.01.27
제네릭 클래스 (Generic class)  (0) 2022.01.25
제네릭 컬렉션 (Generic Collection)  (0) 2022.01.24
Record  (0) 2022.01.21