自定义集合类中的反序列化

时间:2012-01-27 20:18:51

标签: c# .net serialization stream

我有一个自定义集合,它为'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();
            }

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

2 个答案:

答案 0 :(得分:2)

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

其他想法:

  • 除非您在.net 1.1中,否则不要使用ArrayListList<T>会更好
  • 无需子类;延伸方法就足够了
  • 我不建议BinaryFormatter这个...或其他任何真正的

答案 1 :(得分:1)

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