class Program { static void Main(string[] args) { A a = new A() { AppId = "4", haor = "浩然" }; var bytes=a.ObjectToBytes(a); var classA = a.BytesToObject(bytes); Console.ReadKey(); } [Serializable()] public abstract class PacketBase { public string AppId { get; set; } public string Token { get; set; } public string DeviceId { get; set; } } [Serializable()] public class A:PacketBase { public string haor { get; set; } /// <summary> /// 將一個object對象序列化,返回一個byte[] /// </summary> /// <param name="obj">能序列化的對象</param> /// <returns></returns> public byte[] ObjectToBytes(object obj) { using (MemoryStream ms = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); formatter.Serialize(ms, obj); return ms.GetBuffer(); } } /// <summary> /// 將一個序列化後的byte[]數組還原 /// </summary> /// <param name="Bytes"></param> /// <returns></returns> public object BytesToObject(byte[] Bytes) { using (MemoryStream ms = new MemoryStream(Bytes)) { IFormatter formatter = new BinaryFormatter(); return formatter.Deserialize(ms); } } } }