[C#] C++의 Template과 같은 Generic 사용하기 Develop Tip

DotNetFramework 2.0 이상부터 지원되는 Generic 가 있다 합니다.

흡사 C++ 의 템플릿 기능과 유사하다 보면 되겠습니다.

예를 들어, 예전 1.x   버전에서

// The .NET Framework 1.1 way to create a list:
System.Collections.ArrayList list1 = new System.Collections.ArrayList();
list1.Add(3);
list1.Add(105);

System.Collections.ArrayList list2 = new System.Collections.ArrayList();
list2.Add("It is raining in Redmond.");
list2.Add("It is snowing in the mountains.");


위와 같이 각각 object base 를 이용해서 사용하던 것을

// The .NET Framework 2.0 way to create a list
List<int> list1 = new List<int>();

// No boxing, no casting:
list1.Add(3);

List<string> list2 = newList<string>();
list2.Add("It is raining in Redmond.");



위와 같이 사용할 수 있습니다.

그런데 이를 일반적인 클래스에 적용하려다 보니 약간 더 작업을 해야 되더군요.
암튼 아래와 같이 해서 잘 해결하였습니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace caGen
{
    interface Itable<T>
    {
        //static string name;
        string Func();
    }

    class tableA : Itable<tableA>
    {
        static string name = "tableA";
        public string Func()
        {
            return name;
        }
    }
    class tableB : Itable<tableB>
    {
        static string name = "tableB";
        public string Func()
        {
            return name;
        }
    }

    class gen
    {
        public static string doFunc<T>() where T : Itable<T>, new()
        {
            T a = new T();
            return a.Func();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(gen.doFunc<tableA>());
            Console.WriteLine(gen.doFunc<tableB>());
        }
    }
}


덧글

  • 딩딩 2011/12/14 17:42 # 답글

    씨샵은 문자열 써먹기가 편하군요... 애들이 갈아타는 이유가
  • 지훈현서아빠 2011/12/14 20:02 #

    C, C++ 과 같이 문자열을 위한 메모리 관리를 일일이 해야하는 것 보담은,
    Python, Perl, Ruby 등의 스크립트 언어를 포함하여 다른 대부분의 Java, C# 같은
    언어 대부분 위와 같이 문자열을 처리한답니당~
댓글 입력 영역

구글애드텍스트