using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Serialization
{
[Serializable]
class Playable
{
public string name;
public int level;
public long exp;
public Playable()
{
name = "";
level = 1;
exp = 0;
}
}
class Program
{
const string fileName = "SaveData.txt";
static void Main(string[] args)
{
/* 객체 초기화 */
Playable[] characters = new Playable[3];
for(int i = 0; i < 3; ++i)
{
characters[i] = new Playable();
}
characters[0].name = "아라곤";
characters[0].level = 100;
characters[0].exp = 2000;
characters[1].name = "레골라스";
characters[1].level = 98;
characters[1].exp = 1720;
characters[2].name = "김 리";
characters[2].level = 99;
characters[2].exp = 1890;
/* 직렬화 후 데이터 저장 */
FileStream writeStream = new FileStream(fileName, FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(writeStream, characters);
writeStream.Close();
/* 직렬화 된 데이터 읽기 */
FileStream readStream = new FileStream(fileName, FileMode.Open);
BinaryFormatter binaryFormatter2 = new BinaryFormatter();
characters = (Playable[])binaryFormatter2.Deserialize(readStream);
for(int i = 0; i < characters.Length; ++i)
{
Console.WriteLine("Name : {0} \t Level : {1} \t Exp : {2} \t", characters[i].name, characters[i].level, characters[i].exp);
}
readStream.Close();
}
}
}
해당 예제에서는 직렬화가능 속성(Serialization Attribute) 속성을 사용하여 직렬화를 테스트 하였습니다. 기본적으로 이보다 더 많은 제어가 필요한 경우 ISerializable 인터페이스를 상속받아 구현할 수 있습니다. 해당 코드에서는 사용하지 않았지만 ISerializable 인터페이스를 사용하는 경우 GetObjectData() 함수를 재정의하여 데이터 직렬화를 효과적으로 진행할 수 있습니다.
'프로그래밍 > C#' 카테고리의 다른 글
[C#] 기본 데이터 형식 (0) | 2022.04.09 |
---|---|
[C#] using 키워드의 다양한 사용처 (0) | 2021.04.02 |
[C#] Environment.CurrentDirectory와 Directory.GetCurrentDirectory의 차이 (0) | 2021.04.02 |
[C#, LINQ] 내부 조인과 외부 조인 (0) | 2021.03.31 |
[C#] Boxing과 Unboxing (0) | 2021.03.15 |