the*_*e_V 19 .net c# serialization
我正在尝试创建一个类,该类将包含用于将对象序列化/反序列化到字符串/从字符串反序列化的函数.这就是现在的样子:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
SerializeObject方法效果很好,但DeserializeObject没有.我总是得到一个异常,消息"在解析完成之前遇到了流的结束".这可能有什么问题?
dtb*_*dtb 44
使用BinaryFormatter序列化对象的结果是八位字节流,而不是字符串.
您不能将字节视为C或Python中的字符.
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());
}
}
Run Code Online (Sandbox Code Playgroud)
和
public static object DeserializeObject(string str)
{
byte[] bytes = Convert.FromBase64String(str);
using (MemoryStream stream = new MemoryStream(bytes))
{
return new BinaryFormatter().Deserialize(stream);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21795 次 |
| 最近记录: |