NeuroWhAI의 잡블로그

[C#] BinaryFormatter 사용해서 직렬화/역직렬화 본문

개발 및 공부/언어

[C#] BinaryFormatter 사용해서 직렬화/역직렬화

NeuroWhAI 2018. 6. 3. 21:17


[Serializable]가 지정된 클래스만 가능!

코드:
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.InteropServices;
 
namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int data1 = 42;
            double data2 = 2.12;
            string data3 = "Hello, World!";
            
            
            byte[] bytes = null;
            
            BinaryFormatter bf = new BinaryFormatter();
            using(MemoryStream ms = new MemoryStream())
            {
                bf.Serialize(ms, data1);
                bf.Serialize(ms, data2);
                bf.Serialize(ms, data3);
                bytes = ms.ToArray();
            }
            
            Console.WriteLine("{0} bytes", bytes.Length);
            
            
            bf = new BinaryFormatter();
            using(MemoryStream ms = new MemoryStream(bytes))
            {
                object obj = bf.Deserialize(ms);
                Console.WriteLine(data1 == (int)obj);
                
                obj = bf.Deserialize(ms);
                Console.WriteLine(data2 == (double)obj);
                
                obj = bf.Deserialize(ms);
                Console.WriteLine(data3 == (string)obj);
            }
        }
    }
}
cs

150 bytes
True
True
True





Comments