티스토리 뷰

Code/C#

Generic Method 를 이용한 Serialization

Hide Code 2007. 12. 10. 10:00
Generic Method 를 사용하면 상당히 유용한 Serialization 을 구사할 수 있다.

아래 예제는 Generic Method 를 사용하여 어떠한 Type이라도 쉽게 Serialize & Deserialize 할 수 있도록 한 것이다.

이런 것들은 실전에서 유용하게 이용될 수 있다.


using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace GenericSerializer
{
    public static class Serializer
    {
        public static void Export<T>(string otherFile, T otherT)
        {
            using (Stream s = File.Open(otherFile, FileMode.Create))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(s, otherT);
            }
        }

        public static T Import<T>(string otherFile)
        {
            using (Stream s = File.Open(otherFile, FileMode.Open))
            {
                BinaryFormatter bf = new BinaryFormatter();
                object o = bf.Deserialize(s);
                T t = (T)o;
                return t;
            }
        }
    }
}


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
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 27 28
29 30
글 보관함