블로그 이미지
Kanais
Researcher & Developer 퍼즐을 완성하려면 퍼즐 조각들을 하나 둘씩 맞춰나가야 한다. 인생의 퍼즐 조각들을 하나 둘씩 맞춰나가다 보면 인생이란 퍼즐도 완성되는 날이 오려나...?

calendar

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 31

Notice

05-02 15:57

Recent Post

Recent Comment

Recent Trackback

Archive

2015. 5. 19. 11:44 Programming/.NET

작성날짜    : 2011-03-29


참고 : BinaryFormatter Class 

         SoapFormatter Class 

선문비트 프로젝트 - http://cafe.daum.net/smbitpro?t__nil_cafemy=item

 

Serialize(직렬화)
직렬화는 객체의 상태 데이터를 일정한 위치(메모리스트림, 물리적 파일 등)로 지속시키는 것을 말한다. 역 직렬화는 지속된 데이터를 읽어서 읽어들인 상태 값에 기반해서 형식을 재 구성 하는 것을 말한다.

 객체 직렬화는 .NET Remoting 계층에 의해 사용되는 핵심적인 내부 기술이다.

 

직렬화를 하려면 클래스에 [SerializableAttribute 붙여야 한다.

Serialize에서 제외하고 싶은 부분이 있을 경우 해당 필드에 다음과 같이  [NonSerializedAttribute를  써 준다.

[Serializable]

    class Stu : Man

    {

        int num;

[NonSerialized]

int scnt;     // Serialize에서 제외된다.

public Stu(string _name, int _num) : base(_name, 25)

        {

            num = _num;

}

 

BinaryFomatter 형식은 간결한 바이너리 포맷을 이용해 객체 그래프를 스트림으로 직렬화 한다.

멤  버

설  명

Serialize()

관련된 객체들의 객체 그래프를 스트림으로 직렬화 한다.

Deserialize()

바이트 스트림을 객체 그래프로 역직렬화한다.

 

 

 

Serialize를 사용한 소스 코드

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using System.Runtime.Serialization.Formatters.Binary;

using System.Runtime.Serialization.Formatters.Soap;

using System.Runtime.Serialization;

 

namespace ExampleSerialize

{

    [Serializable]

    class Man

    {

        string name;

        int age;

 

        public Man(string _name, int _age)

        {

            name = _name;

            age = _age;

        }

        public override string ToString()

        {

            return string.Format("이름:{0} 나이:{1}", name, age);

        }

    }

[Serializable]

    class Stu : Man

    {

        int num;
        
int scnt;
        
public Stu(string _name, int _num) : base(_name, 25)

        {

            num = _num;
            
scnt = 30;
        
}
        
public override string ToString()

        {

            return "학생입니다." + base.ToString() 
                 
string.Format("번호:{0} 카운터{1}", num, scnt);

  }

 

 

BinaryFormatter를 이용한 직렬화, 역직렬화

class Program

    {

        static void Main(string[] args)

        {

            #region BinaryFormatter를 이용한 직렬화

            Stu stu = new Stu("홍길동"3);

            FileStream fs = new FileStream("data.txt",FileMode.Create);

 

            BinaryFormatter bf = new BinaryFormatter();

            bf.Serialize(fs, stu);

            fs.Close();

            #endregion

 

            #region BinaryFormatter를 이용한 역직렬화

 

            Stu s;

            FileStream fs = new FileStream("data.txt"FileMode.Open);

            BinaryFormatter bf = new BinaryFormatter();

            s = bf.Deserialize(fs) as Stu;

            fs.Close();

            Console.WriteLine(s.ToString());

            #endregion

}

    }

 

역직렬화 했을 때 출력 결과

 

 

BinaryFormatter를 사용하여 생성 된 파일

이진 형식이기 때문에 글자가 제대로 보이지 않는다.

 


SoapFormatter
를 사용한 직렬화, 역직렬화

SoapFormatter를 사용하기 위해서는 System.Runtime.Serialization.Formatters.Soap.dll 을 참조해야 한다.


class Program

    {

        static void Main(string[] args)

        {

            #region SoapFormatter를 이용한 역직렬화

            Stu stu = new Stu("홍길동"3);

            FileStream fs = new FileStream("data.xml"FileMode.Create);

            SoapFormatter sf = new SoapFormatter();

            sf.Serialize(fs, stu);

            fs.Close();

            #endregion

 

            #region SoapFormatter를 이용한 역직렬화

            Stu s;

            FileStream fs = new FileStream("data.xml"FileMode.Open);

            SoapFormatter sf = new SoapFormatter();

            s = sf.Deserialize(fs) as Stu;

            fs.Close();

            Console.WriteLine(s.ToString());

            #endregion

        }

    }

 

역직렬화 했을 때 출력 결과


SoapFormatter를 사용하여 생성된 파일

BinaryFormatter를 사용하여 생성된 파일과는 다르게 내용을 제대로 볼 수 있다.


사용자 정의 직렬화

 [Serializable]

    class Stu : Man,ISerializable

    {

        int num;

        int scnt;

        public Stu(string _name, int _num)

            : base(_name, 25)

        {

            num = _num;

            scnt = 30;

        }

protected Stu(SerializationInfo info, StreamingContext context)

:base(string.Empty,0)

        {

            num =(int) info.GetValue("번호",num.GetType()) ;

        }

        public override string ToString()

        {

            return "학생입니다." + base.ToString()

string.Format("번호:{0} 카운터{1}", num,scnt);

        }

        #region ISerializable 멤버

        public void GetObjectData(SerializationInfo info, StreamingContext context)

        {

            info.AddValue("번호", num);

        }

        #endregion

    }

 

출력 결과

결과를 보면 번호만 출력된 것을 확인할 수 있다.



posted by Kanais