Csharp/C#教程:二进制序列化和反序列化而不创建文件(通过字符串)分享


二进制序列化和反序列化而不创建文件(通过字符串)

我正在尝试创建一个类,该类将包含用于将对象序列化/反序列化到字符串/从字符串反序列化的函数。 这就是现在的样子:

public class BinarySerialization { public static string SerializeObject(object o) { string result = ""; if ((o.GetType().Attributes & TypeAttributes.Serializable) == TypeAttributes.Serializable) { BinaryFormatter f = new BinaryFormatter(); using (MemoryStream str = new MemoryStream()) { f.Serialize(str, o); str.Position = 0; StreamReader reader = new StreamReader(str); result = reader.ReadToEnd(); } } return result; } public static object DeserializeObject(string str) { object result = null; byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str); using (MemoryStream stream = new MemoryStream(bytes)) { BinaryFormatter bf = new BinaryFormatter(); result = bf.Deserialize(stream); } return result; } } 

SerializeObject方法效果很好,但DeserializeObject却没有。 我总是得到一个exception消息“解析完成之前遇到的流结束”。 这可能有什么问题?

使用BinaryFormatter序列化对象的结果是八位字节流,而不是字符串。
您不能将字节视为C或Python中的字符。

使用Base64对序列化对象进行编码以获取字符串:

 public static string SerializeObject(object o) { if (!o.GetType().IsSerializable) { return null; } using (MemoryStream stream = new MemoryStream()) { new BinaryFormatter().Serialize(stream, o); return Convert.ToBase64String(stream.ToArray()); } } 

 public static object DeserializeObject(string str) { byte[] bytes = Convert.FromBase64String(str); using (MemoryStream stream = new MemoryStream(bytes)) { return new BinaryFormatter().Deserialize(stream); } } 

对编码和解码使用UTF8 Base64编码而不是ASCII。

上述就是C#学习教程:二进制序列化和反序列化而不创建文件(通过字符串)分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1003132.html

(0)
上一篇 2021年12月27日
下一篇 2021年12月27日

精彩推荐