【问题标题】:Exceptions while using BinaryFormatter to deserialize my serialized data使用 BinaryFormatter 反序列化我的序列化数据时出现异常
【发布时间】:2010-12-17 18:29:30
【问题描述】:

我使用BinaryFormatterMemoryStream 来序列化一个对象,然后将它作为二进制blob 存储在数据库中。然后我从数据库中检索数据并使用 binaryformatter 和内存流进行反序列化。

但是,当我尝试反序列化对象时,我经常会抛出异常。最值得注意的是'an object with the same key already exists''cannot convert string to int64'

有没有人知道为什么反序列化会失败?或者如何找出哪个字典对象有问题?

我的序列化函数如下...

private byte[] SerializeUserData(UserData ud)
{
    byte[] data = null;
    using (MemoryStream ms = new MemoryStream())
    {
        ms.Seek(0, SeekOrigin.Begin);
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(ms, ud);
        data = ms.ToArray();
    }
    return data;
}

private UserData Deserialize()
{
    UserData ud = null;
    using (MemoryStream ms = new MemoryStream(mSession.BinarySession))
    {
        BinaryFormatter bf = new BinaryFormatter();
        ud = bf.Deserialize(ms) as UserData;
    }
    return ud; 
}

UserData 类有点像怪物,但它被标记为 [serializable] 并且其对象树中的所有类也被标记为 [serializable]。本课程的部分内容如下:

[Serializable]
public class UserData
{
        public UserData() { Clear(); }
        public Guid Id { get; set; }

        public Account Account { get; set; }
        public List<Account> OldAccounts{ get; set; }

        public void Clear()
        {
          Account = null;
          OldAccounts = new List<Account>();
          Id = Guid.NewGuid();
        }
}

【问题讨论】:

  • UserData 类是否实现了ISerializable 接口?
  • 你能提供一些关于 UserData 类型的细节吗?
  • 它是否使用完全相同版本的对象 dll 进行了序列化和反序列化?顺便说一句,我强烈建议不要在数据库上使用 BF;首选基于合同且独立于平台的东西,例如 protobuf。 BF最终会伤害你
  • 看看那个样本,我认为我们需要 Account 来重现...基本上需要重现它才能真正回答。
  • 另外,你确定你已经从数据库中读取了整个 BLOB 吗?很容易不小心只读取了第一个块。

标签: c# serialization memorystream binaryformatter


【解决方案1】:

我在最近版本的框架中没有尝试过这个,但我认为经验法则可能仍然很好,不要使用带有自动属性的 BinaryFormatter。

问题是,BinaryFormatter 使用支持字段而不是属性来进行序列化/反序列化。在自动属性的情况下,支持字段是在编译时生成的。而且不保证每次都一样。这可能意味着您反序列化了您的对象,而您并不能准确地返回您输入的内容。

更多信息请阅读:Automatic Properties and the BinaryFormatter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 2015-12-09
    • 2014-12-10
    • 1970-01-01
    相关资源
    最近更新 更多