我有一个自定义集合,它为'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();
}
我应该如何使用已反序列化的内容填充集合?
答案 0 :(得分:2)
BinaryFormatter
不支持将序列化为现有对象。您可以将其反序列化为新列表 - 只需将其设为static
方法并返回值。
其他想法:
ArrayList
:List<T>
会更好BinaryFormatter
这个...或其他任何真正的答案 1 :(得分:1)
方法BinaryFormatter.Deserialize()创建一个新对象,使用流中的数据对其进行初始化并返回它。因此,您应该使用返回值并将其用作新的ArrayList
对象。 Read
方法因此进入静态方法,或者 - 如 diggingforfire 建议 - 进入另一个类。