二进制序列化的问题

dubuyunjie dubuyunjie 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
各位大神好,我有这样一个问题。
这是我要序列化的数据结构,每次序列化一个CDetails 。里面含有一个list
[Serializable]
public class CDetail
{
public double Amout
{
get { return _amout; }
set { _amout = value; }
}

public string Type
{
get { return _type; }
set { _type = value; }
}

public string OtherType
{
get { return _otherType; }
set { _otherType = value; }
}

public string Remark
{
get { return _remark; }
set { _remark = value; }
}


private double _amout;
private string _type;
private string _otherType;
private string _remark;
}

[Serializable]
public class CDetails
{
/// <summary>
/// 1为CEO,2为董事长
/// </summary>
[DefaultValue(1)]
public int CEOOrChairMan;

private List<CDetail> _listDetail = new List<CDetail>();
public List<CDetail> listDetail
{
get { return _listDetail; }
set { _listDetail = value; }
}

public void Add(CDetail c)
{
listDetail.Add(c);
}
}


序列化和反序列化的代码如下
/// <summary>
/// 序列化 对象到字符串
/// </summary>
/// <param name="obj">泛型对象</param>
/// <returns>序列化后的字符串</returns>
public static string Serialize<T>(T obj)
{
try
{
BinaryFormatter formatter = new BinaryFormatter();
MemoryStream stream = new MemoryStream();
formatter.Serialize(stream, obj);
stream.Position = 0;
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Flush();
stream.Close();
return System.Convert.ToBase64String(buffer);
}
catch (Exception ex)
{
throw new Exception("序列化失败,原因:" + ex.Message);
}
}

/// <summary>
/// 反序列化 字符串到对象
/// </summary>
/// <param name="obj">泛型对象</param>
/// <param name="str">要转换为对象的字符串</param>
/// <returns>反序列化出来的对象</returns>
public static T Desrialize<T>(T obj, string str)
{
try
{
//obj = default(T);
BinaryFormatter formatter = new BinaryFormatter();
//formatter.Binder = new BindChanger();
byte[] buffer =System.Convert.FromBase64String(str);
MemoryStream stream = new MemoryStream();
stream.Write(buffer,0,buffer.Length);
stream.Position = 0;
obj = (T)formatter.Deserialize(stream);
stream.Flush();
stream.Close();
}
catch (Exception ex)
{
throw new Exception("反序列化失败,原因:" + ex.Message);
}
return obj;
}


之前一个版本用着好好的,可以序列化可以显示。
但是不知道怎么的,我这最新的代码,我看了svn,没有改动,最新的程序不能反序列化以前的数据,体现在反序列化之后那个list为null。如果把这个程序集换成以前的,就可以。我现在在反序列化的时候加了
formatter.AssemblyFormat = FormatterAssemblyStyle.Simple;
这个,也不行。其它我实在想不到什么原因了。请各位赐教~
...全文
评论 4
收藏 已收藏
分享
返回顶部
dubuyunjie
C# 111,128 成员 642,537 内容