728x90
반응형
02. 직렬화(serialize)
직렬화(serialize)
- StreamWriter / StreamReader와 BinaryWriter / BinaryReader
=> 기본 데이터형만 저장 및 읽기
- 구조체, 클래스 저장 및 읽기
=> FileStream, BinaryFormatter
- BinaryFormatter 네임스페이스
=> using System.Runtime.Serialization.Formatters.Binary;
직렬화 대상 설정
-
대상 설정
[Serializable]
struct A
{
}
[Serializable]
class A
{
}
BinaryFormatter
public void Serialize(
Stream serializtionStream,
object graph
)
public object Deserialize( // Deserialize: 저장되어있는 데이터를 다시 읽어 낸다.
Stream serializtionStream
)
구조체의 내용을 저장하고 읽기
6-12 예제)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace _6_12
{
[Serializable] //구조체 명시해줘야 한다.
struct DATA
{
public int var1;
public float var2;
public string str1;
}
class Program
{
static void Main(string[] args)
{
DATA[] Data = new DATA[2];
Data[0].var1 = 1;
Data[0].var2 = 0.5f;
Data[0].str1 = "Test1";
Data[1].var1 = 2;
Data[1].var2 = 1.5f;
Data[1].str1 = "Test2";
using (FileStream fs1 =
new FileStream("test.dat", FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter(); // 바이너리포메터 생성
bf.Serialize(fs1, Data);
}
DATA[] ResultData;
using (FileStream fs2 = new FileStream("test.dat", FileMode.Open))
{
BinaryFormatter bf2 = new BinaryFormatter();
ResultData = (DATA[])bf2.Deserialize(fs2);
}
for (int i = 0; i < 2; i++)
{
Console.WriteLine("{0} {1} {2}", ResultData[i].var1,
ResultData[i].var2, ResultData[i].str1);
}
}
}
}
역직렬화(deserialize)
- 역직렬화: 직렬화 대상에서 제외
- [NonSerialize]'
[Serializblre]
class testClass
{
int nValue;
[NonSerialize]
string strMessage; // 또는 [NinSerialze] string strMessage;
)
6-13 예제)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace _6_13
{
[Serializable]
struct DATA
{
public int var1;
public float var2;
[NonSerialized]
public string str1;
}
class Program
{
static void Main(string[] args)
{
DATA[] Data = new DATA[2];
Data[0].var1 = 1;
Data[0].var2 = 0.5f;
Data[0].str1 = "test1";
Data[1].var1 = 2;
Data[1].var2 = 1.5f;
Data[1].str1 = "test2";
using (FileStream fs1 =
new FileStream("test.dat", FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs1, Data);
}
DATA[] ResultData;
using (FileStream fs2 = new FileStream("test.dat", FileMode.Open))
{
BinaryFormatter bf2 = new BinaryFormatter();
ResultData = (DATA[])bf2.Deserialize(fs2);
}
for (int i = 0; i < 2; i++)
{
Console.WriteLine("{0} {1} {2}", ResultData[i].var1,
ResultData[i].var2, ResultData[i].str1);
}
}
}
}
컬렉션의 직렬화
- 컬렉션과 제네릭, 같은 데이터형의 임의의 메모리 또는 연속적인 메모리를 다룰 수 있도록 하는 클래스
- ArrayList, List<T>
- 제네릭을 이용한 직렬화
6-14 예제)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
namespace _6_14
{
[Serializable]
struct Data
{
public int data;
public string str;
public Data(int data1, string str1)
{
data = data1;
str = str1;
}
}
class Program
{
static void Main(string[] args)
{
List<Data> ResultList;
List<Data> DataList = new List<Data>();
DataList.Add(new Data(7, "test1"));
DataList.Add(new Data(12, "test2"));
DataList.Add(new Data(12, "test2"));
DataList.Add(new Data(12, "test2"));
DataList.Add(new Data(12, "test2"));
using (FileStream fs1 = new FileStream("test.dat",
FileMode.Create))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs1, DataList);
}
using (FileStream fs2 = new FileStream("test.dat", FileMode.Open))
{
BinaryFormatter bf2 = new BinaryFormatter();
ResultList = (List<Data>)bf2.Deserialize(fs2);
}
for (int i = 0; i < 5; i++)
{
Console.WriteLine("{0} {1}", ResultList[i].data, ResultList[i].str);
}
}
}
}
파일 입출력 정리
입출력 단위 | 클래스 | 사용빈도 |
바이트 | File, FileStream + BitConverter | * |
텍스트 | StreamWriter, StreamReader + FileStream | *** |
이진 | BinaryWriter, BinaryReader + FileStream | ***** |
구조체와 클래스 | [Serializable] + BinaryFormatter [Serializable] + 컬렉션 + BinaryFormatter |
****** |
728x90
반응형
'C# > C#으로 살아남기_나우캠퍼스_이태성강사' 카테고리의 다른 글
[C# 언어 8강] 클래스(2/2) 객체 생성 및 사용, 클래스 참조와 this (0) | 2021.03.09 |
---|---|
[C# 언어 8강] 클래스(1/2) 개요, 클래스 형식과 접근 한정자 (0) | 2021.03.09 |
[C# 언어 6강] 파일입출력(2/3) 파일스트림2 (0) | 2021.03.03 |
[C# 언어 6강] 파일입출력(1/3) 파일스트림1 (0) | 2021.03.02 |
[C# 언어 5강] 배열 (3/3) 배열을 리턴하는 함수, 배열의 메서드 (0) | 2021.03.01 |