[C#] 제네릭 ( Generics )

|

제네릭이란 .NET 2.0에서 새롭게 추가된 개념입니다.

제네릭을 통해서 형식 매개변수(type parameter)라는 개념이 도입되었습니다.  형식 매개변수를 사용해서 클래스나 매서드를 사용하면 그것이 인스턴스화 될때까지 형식지정을 연기할 수 있습니다.


즉, 동일한 기능을 수행하지만 입력받는 타입만 다를 경우 모두 다른 클래스나 메서드를 생성해야 하지만 

제네릭을 이용하면 하나만 선언해주고 클라이언트 코드에서 어떤 타입으로 사용할 것인지를 결정해주면 됩니다. 

또한 이에 따른 Boxing작업이 일어나지 않고 처리가 됩니다. C++의 템플릿 기능과 비슷하다고 보면됩니다.


간단한 예를 들어 보겠습니다.

아래의 예제는 사용자 정의 스택을 List로 구현한 것입니다.


1. 제네릭 클래스 선언

 public class HongsStack<T>
{
    private List<T> data;

    public HongsStack()
    {
        data = new List<T>();
    }

    //데이터 넣기
    public bool Push(T _value)
    {
        try
        {
            //쓰레드 안전
            lock(data)
            {
                this.data.Add(_value);
                return true;
            }
        }
        catch (Exception)
        {

            return false;
        }
    }

    //데이터 출력
    public T Pop()
    {
        try
        {
            lock (data)
            {
                if (this.data.Count.Equals(0))
                {
                    return default(T);
                }

                T returnData = this.data[this.data.Count - 1];
                this.data.RemoveAt(this.data.Count - 1);
                return returnData;
            }
        }
        catch (Exception)
        {
            
            throw;
        }
    }

    //스택 카운트 확인
    public int GetStackCount()
    {
        try
        {
            lock(data)
            {
                return this.data.Count;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }
    
}
 

우선 클래스이름을 HongsStack<T> 로 선언해서 제네릭을 사용한다고 선언해줍니다.

클래스 내에서 입력받은 타입으로 변환되어야 할 모든 타입을 T로 선언해줍니다. 이렇게 해주면 클라이언트 코드에서

인스턴스화 해주면, 그때 클래스의 T 가 해당 입력받은 타입으로 모두 변환된다고 보시면 됩니다.



 2.제네릭 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
HongsStack<int> intStack = new HongsStack<int>();
intStack.Push(1);
intStack.Push(2);
intStack.Push(3);
Console.WriteLine(intStack.Pop().ToString());
Console.WriteLine(intStack.Pop().ToString());
intStack.Push(4);
Console.WriteLine(intStack.GetStackCount().ToString());
 
 
HongsStack<string> stringStatck = new HongsStack<string>();
stringStatck.Push("홍진현");
stringStatck.Push("NET");
stringStatck.Push("C#");
Console.WriteLine(stringStatck.Pop());
Console.WriteLine(stringStatck.Pop());
stringStatck.Push("ForMVP");
Console.WriteLine(stringStatck.GetStackCount().ToString());
 
//결과
//3
//2
//2
//C#
//NET
//2
cs

사용은 HongsStack<int> 나 HongsStack<string> 으로 해서 선언을 해주면 됩니다.

이처럼 동일한 기능을 수행하지만 타입이 다를경우에는 제네릭을 이용하면 유연한 클래스를 만들수 있습니다.




And