/// <summary> /// 将可序列化对象转成Byte数组 /// </summary> /// <param name="obj">对象(对象不能为空)</param> /// <returns>返回相关数组</returns> protected static byte[] ObjectToByteArray<T>(T obj) where T : ISerializable { if (obj == null) { byte[] byteArr = new byte[] { }; return byteArr; } else { MemoryStream ms = new MemoryStream(); BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(ms, obj); ms.Close(); return ms.ToArray(); } } /// <summary> /// 将可序列化对象转成的byte数组还原为对象 /// </summary> /// <param name="byteArry">byte数组</param> /// <returns>相关对象</returns> protected static T ByteArrayToObject<T>(byte[] byteArry) where T : ISerializable { if (byteArry != null && byteArry.Length > 0) { MemoryStream ms = new MemoryStream(byteArry); BinaryFormatter bf = new BinaryFormatter(); return (T)bf.Deserialize(ms); } else { return default(T); } }
时间: 2024-10-06 19:59:30