Serialization ใน C#.NET
Serialization คือกระบวนการแปลงอ็อบเจกต์เป็น Byte Stream เพื่อบันทึกลงไฟล์ หน่วยความจำ ฐานข้อมูล หรือส่งผ่านเครือข่าย การทำอย่างกลับกันคือ Deserialization
ประเภทหลัก 2 แบบ
1. Binary Serialization
- Serialize ทุก Member (private, public, readonly)
- รักษา Object Graph (References, Circular References)
- ไบนารีขนาดเล็ก เร็ว แต่ไม่ Human-Readable
- ใช้
BinaryFormatter(Deprecated ใน .NET 5+ เนื่องจาก Security)
2. XML Serialization
- Serialize เฉพาะ Public Fields/Properties
- ผลลัพธ์เป็น XML ที่อ่านง่าย Interoperable
- ใช้
XmlSerializer - ต้องมี Parameterless Constructor
ตัวอย่าง Binary Serialization (Legacy)
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public Employee(int id, string name, string dept)
{
Id = id; Name = name; Department = dept;
}
}
class Program
{
static void Main()
{
Employee emp = new Employee(30, "Tom", "Operations");
// Serialize
using (FileStream fs = new FileStream("emp.dat", FileMode.Create))
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, emp);
}
// Deserialize
using (FileStream fs = new FileStream("emp.dat", FileMode.Open))
{
BinaryFormatter formatter = new BinaryFormatter();
Employee emp2 = (Employee)formatter.Deserialize(fs);
Console.WriteLine($"{emp2.Id}, {emp2.Name}, {emp2.Department}");
}
}
}
ตัวอย่าง XML Serialization (แนะนำ)
using System;
using System.IO;
using System.Xml.Serialization;
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Department { get; set; }
public Employee() {} // Required for XmlSerializer
public Employee(int id, string name, string dept) { Id=id; Name=name; Department=dept; }
}
class Program
{
static void Main()
{
Employee emp = new Employee(30, "Tom", "Operations");
XmlSerializer serializer = new XmlSerializer(typeof(Employee));
// Serialize to file
using (FileStream fs = new FileStream("emp.xml", FileMode.Create))
{
serializer.Serialize(fs, emp);
}
// Deserialize
using (FileStream fs = new FileStream("emp.xml", FileMode.Open))
{
Employee emp2 = (Employee)serializer.Deserialize(fs);
Console.WriteLine($"{emp2.Id}, {emp2.Name}, {emp2.Department}");
}
}
}
ผลลัพธ์ XML (emp.xml)
30
Tom
Operations
ตัวเลือกสมัยใหม่ (Modern Alternatives)
- System.Text.Json (Built-in .NET Core 3.0+) - เร็ว, รองรับ UTF-8, แนะนำสำหรับ Web API
- Newtonsoft.Json (Json.NET) - Feature-rich, Popular
- Protobuf / MessagePack - Binary, Compact, Fast, Cross-language