C# C++의 Template과 같은 Generic으로 Custom Generic Class 만들어보기

 C++의 템플릿을 C#에서는 제네릭이라고 하네요. 기본적으로 System.Collections.Generic에 있는 Dictionary<,> 등은 자주 사용했는데 커스텀 된 제네릭은 만들어보지 않아서 이번에 유니티3D에서 게임 데이터 시리얼자이즈/디시리얼라이즈 객체 만들면서 필요하게 되서 C#의 커스텀 제네릭 간단한 사용법을 정리해봅니다. 초간단한 내용이므로 C#을 잘 하시는분은 패스하셔도 됩니다.

 먼저 간단하게 C++ 템플릿과 C# 제너릭의 차이점을 정리해보면 C# 제네릭이 C++의 템플릿처럼 복잡하지 않고 간편하게 다룰 수 있다가 되겠습니다. C++ 템플릿에서는 지원하는 특징들이 C# 제네릭에서는 사용할 수 없게 제한이 되어있기 때문에 더욱 간편한 듯하네요. 자세한 차이점은 MSDN 링크를 확인하세요.

C++에서는

template<class T>
class MyTemplate
{
...
};

 이렇게 했다면, C#은 간단해졌네요. template구문이 필요없네요.

class MyTemplate<T>
{
...
};

 이렇게 간단하게 끝내면 섭하죠? 아래는 역시나 MSDN의 제네릭 소개 부분의 코드를 긁어와 봤습니다. 보통은 아래처럼 안하고 이미 .NET Framework에 있는 LIst<T>를 사용하겠지만 예제니까요.


// type parameter T in angle brackets
public class GenericList<T> 
{
    // The nested class is also generic on T.
    private class Node
    {
        // T used in non-generic constructor.
        public Node(T t)
        {
            next = null;
            data = t;
        }

        private Node next;
        public Node Next
        {
            get { return next; }
            set { next = value; }
        }

        // T as private member data type.
        private T data;

        // T as return type of property.
        public T Data  
        {
            get { return data; }
            set { data = value; }
        }
    }

    private Node head;

    // constructor
    public GenericList() 
    {
        head = null;
    }

    // T as method parameter type:
    public void AddHead(T t) 
    {
        Node n = new Node(t);
        n.Next = head;
        head = n;
    }

    public IEnumerator<T> GetEnumerator()
    {
        Node current = head;

        while (current != null)
        {
            yield return current.Data;
            current = current.Next;
        }
    }
}


 아래는 위에서 만든 GenericList<T>를 사용하는 main부분입니다. int로 넘겨줬지만 string나 사용자 정의 객체를 사용해도 무방하겠죠.


class TestGenericList
{
    static void Main()
    {
        // int is the type argument
        GenericList<int> list = new GenericList<int>();

        for (int x = 0; x < 10; x++)
        {
            list.AddHead(x);
        }

        foreach (int i in list)
        {
            System.Console.Write(i + " ");
        }
        System.Console.WriteLine("\nDone");
    }
}


 간단하게 정리해봤습니다. 위에 MSDN 링크에는 이외에도 많은 내용들이 있네요. 역시 공부할게 많아요~

댓글

이 블로그의 인기 게시물

'xxx.exe' 프로그램을 시작할 수 없습니다. 지정된 파일을 찾을 수 없습니다.

goorm IDE에서 node.js 프로젝트로 Hello World Simple Server 만들어 띄워보기

애드센스 수익을 웨스턴 유니온으로 수표대신 현금으로 지급 받아보자.