【问题标题】:Deserialization in Custom Collection Class自定义集合类中的反序列化
【发布时间】:2012-01-27 20:18:51
【问题描述】:

我有一个自定义集合,它为“ArrayList”类添加了功能。

这是该课程的一些代码:

    [Serializable]
    class Coll : ArrayList
    {

       public void Save(string path)
            {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream fsOut = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
                formatter.Serialize(fsOut, this);
                fsOut.Dispose();
            }
    }

我现在正试图反序列化一个文件,并用文件的内容填充集合。基本上与我的Save(string path) 方法相反。

这是我目前得到的:

public void Read(string path)
            {
                BinaryFormatter formatter = new BinaryFormatter();
                FileStream fsIn = new FileStream(path, FileMode.Open, FileAccess.Read);
                formatter.Deserialize(fsIn);
                fsIn.Dispose();
            }

我应该如何使用已反序列化的内容填充集合?

【问题讨论】:

  • 为什么不用Deserialize的返回值?
  • 这就是我坚持的部分。我应该如何从该输出中填充数组?
  • 从集合中取出(反)序列化位,a collection should be for storing things。然后将整个集合作为一个整体反序列化(尽管您可以使用扩展方法来实现相同的语法)
  • 你可以做类似 Coll other = formatter.Deserialize(fsIn) as Coll; foreach (var item in other){ this.Add(item); } 但它带来了很大的开销,并且根据定义是不可靠的。最好在你的集合之外声明你的序列化逻辑
  • 或者使 Read 方法静态返回 formatter.Deserialize(fsIn) 转换为 Coll 的结果

标签: c# .net serialization stream


【解决方案1】:

BinaryFormatter 不支持序列化现有对象。您可以将其反序列化为 new 列表 - 只需将其设为 static 方法并返回值。

其他想法:

  • 除非您在 .net 1.1 中,否则不要使用 ArrayListList<T> 会更好
  • 不需要子类;一个扩展方法就足够了
  • 我不推荐 BinaryFormatter 这个...或者其他任何东西

【讨论】:

  • 从技术上讲,您可以使用序列化代理将序列化为现有对象。但这样做可能不是一个好主意。
【解决方案2】:

BinaryFormatter.Deserialize() 方法创建一个新对象,使用流中的数据对其进行初始化并返回它。因此,您应该使用返回值并将其用作新的ArrayList 对象。 Read 方法因此进入一个静态方法,或者 - 正如 diggingforfire 建议的那样 - 进入另一个类。

【讨论】:

    猜你喜欢
    • 2017-01-04
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 2012-11-29
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    相关资源
    最近更新 更多