使用 C# 序列化物件
最近常遇到將物件序列化的問題,
想說乾脆將物件序列化的方法寫成一個工具,稱為 SerialzationHelper,
套上泛型就可以適用在所有的物件了。(當然該物件必須是 serializable 的才可以啦)
Book 是用來測試的可序列化類別,
Main 是使用序列化的過程,
SerialzationHelper 是序列化工具。
完整範例:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Serializable] | |
/// <summary> Book Class </summary> | |
internal class Book | |
{ | |
/// <summary> Book Name </summary> | |
public string Name { get; set; } | |
/// <summary> Book ID </summary> | |
public int Id { get; set; } | |
/// <summary> Book PublishDate </summary> | |
public DateTime PublishDate { get; set; } | |
/// <summary> Book RawData </summary> | |
public byte[] RawData { get; set; } | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void Main(string[] args) | |
{ | |
Book book = new Book(); | |
book.Name = "Test Book"; | |
book.Id = 12345; | |
book.PublishDate = DateTime.Now; | |
book.RawData = new byte[] {1, 2, 3}; | |
byte[] data = SerialzationHelper.BinarySerialize(book); | |
Book book2 = SerialzationHelper.BinaryDeserialize<Book>(data); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> SerialzationHelper Class </summary> | |
public class SerialzationHelper | |
{ | |
/// <summary> Serialize object to binary </summary> | |
/// <param name="obj"> object </param> | |
/// <returns> binary </returns> | |
public static byte[] BinarySerialize(object obj) | |
{ | |
byte[] data; | |
IFormatter formatter = new BinaryFormatter(); | |
using (var stream = new MemoryStream()) | |
{ | |
formatter.Serialize(stream, obj); | |
data = stream.GetBuffer(); | |
} | |
return data; | |
} | |
/// <summary> Deserialize binary to object </summary> | |
/// <typeparam name="T"> object type </typeparam> | |
/// <param name="data"> binary </param> | |
/// <returns> object </returns> | |
public static T BinaryDeserialize<T>(byte[] data) | |
{ | |
T obj; | |
IFormatter formatter = new BinaryFormatter(); | |
using (var stream = new MemoryStream(data)) | |
{ | |
obj = (T)formatter.Deserialize(stream); | |
} | |
return obj; | |
} | |
} |
Basic Serialization
BinaryFormatter 類別
MemoryStream 類別
using Statement (C# Reference)
沒有留言:
張貼留言