페이지

2013년 1월 23일 수요일

Generic Tuple in C# without .NET 4.0

Unity3D에서 Tuple을 사용해보려니 .Net 2.0 에서는 지원이 안된다.

그래서 직접 만들어보기로 함..

namespace를 내 이름으로 하고 사용하니 왠지 기분이 좋아졌다~ (이런 뵨태기질;;)

어쨋든~! Tuple은 여러가지 데이터형을 순열로 사용할때 정말 유용한거 같다.

앞으로 자주 사용할 듯~ (아래 코드의 안전성은 보장 못함...)



// Generic Tuple

using System;
using System.Collections.Generic;

namespace Claire
{  
    public class Tuple<T1, T2>
    {
        public T1 First { get; private set; }
        public T2 Second { get; private set; }
        internal Tuple(T1 first, T2 second)
        {
            First = first;
            Second = second;
        }
    }

    public class Tuple<T1, T2, T3>
    {
        public T1 First { get; private set; }
        public T2 Second { get; private set; }
        public T3 Third { get; private set; }
        internal Tuple(T1 first, T2 second, T3 third)
        {
            First = first;
            Second = second;
            Third = third;
        }
    }

    public static class Tuple
    {
        public static Tuple<T1, T2> Create<T1, T2>(T1 first, T2 second)
        {
            var tuple = new Tuple<T1, T2>(first, second);
            return tuple;
        }

        public static Tuple<T1, T2, T3> Create<T1, T2, T3>(T1 first, T2 second, T3 third)
        {
            var tuple = new Tuple<T1, T2, T3>(first, second, third);
            return tuple;
        }
    }
}


// how to use

using Claire;

Tuple<int , float , string > doSomthing()
{
     Tuple< int, float, string> tuple = new Tuple< int, float, string>(8, 0.5f, "hello");
     return tuple;
}

void Example () {

        Tuple< int, float, string> tuple = doSomthing();

        var item1 = tuple.First;
        var item2 = tuple.Second;
        var item3 = tuple.Third;
}

댓글 없음:

댓글 쓰기