การแปลง Object ให้อยู่ในรูปแบบ Binary ซึ่งไม่ได้อยู่ในรูปแบบที่มนุษย์สามารถอ่านได้ เรียกว่า Binary Serialization
การแปลงกลับรูปแบบไบนารีเป็นรูปแบบที่มนุษย์อ่านได้เรียกว่าดีซีเรียลไลเซชัน?
เพื่อให้บรรลุการทำให้เป็นอันดับไบนารีใน C # เราต้องใช้ไลบรารี System.Runtime.Serialization.Formatters.Binary การประกอบ
สร้างวัตถุของคลาส BinaryFormatter และใช้วิธีการทำให้เป็นอนุกรมภายในคลาส
ตัวอย่าง
Serialize an Object to Binary
[Serializable]
public class Demo {
public string ApplicationName { get; set; } = "Binary Serialize";
public int ApplicationId { get; set; } = 1001;
}
class Program {
static void Main() {
Demo sample = new Demo();
FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fileStream, sample);
Console.ReadKey();
}
} ผลลัพธ์
ÿÿÿÿ
AConsoleApp เวอร์ชัน =1.0.0.0 วัฒนธรรม =เป็นกลาง PublicKeyToken =null ConsoleApp.Demo
ตัวอย่าง
Converting back from Binary to Object
[Serializable]
public class Demo {
public string ApplicationName { get; set; }
public int ApplicationId { get; set; }
}
class Program {
static void Main() {
FileStream fileStream = new FileStream(@"C:\Temp\Questions.dat ", FileMode.Open);
BinaryFormatter formatter = new BinaryFormatter();
Demo deserializedSampledemo = (Demo)formatter.Deserialize(fileStream);
Console.WriteLine($"ApplicationName { deserializedSampledemo.ApplicationName} --- ApplicationId { deserializedSampledemo.ApplicationId}");
Console.ReadKey();
}
} ผลลัพธ์
ApplicationName Binary Serialize --- ApplicationId 1001