我正在使用序列化保存我的班级列表。这部分工作正常,当我尝试反序列化时,它没有做任何事情。
private class Company : ISerializable
{
public string Name;
public System.IO.FileSystemWatcher Watch;
public string Email;
}
方法:
public Company(SerializationInfo info, StreamingContext ctxt)
{
Name = (String)info.GetValue("Name", typeof(string));
Watch.Path = (String)info.GetValue("Watch Path", typeof(string));
Email = (String)info.GetValue("Email address", typeof(string));
}
最后是序列化本身:
Stream stream = File.Open(User + ".osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();
bformatter.Serialize(stream, CompanyList);
stream.Close();
CompanyList
是包含Company
类对象的列表。当我检查文件时,它就完美无缺。但是,当我尝试反序列化到CompanyList
时,它不起作用。它没有错误,只是没有回馈任何信息。
我刚刚开始使用序列化,所以我确定搞砸了。
编辑反序列化代码:
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
info.AddValue("Name", Name);
info.AddValue("Watch Path", Watch.Path);
info.AddValue("Email address", Email);
}
看起来像这样。然后我称之为将其作为公司列表:
(List<Company>)bformatter.Deserialize(stream);
答案 0 :(得分:1)
反序列化构造函数可能会抛出异常,因为FileSystemWatcher
为null。
您正在设置Path
对象的Watch
属性,但是您没有初始化实际的Watch
对象,至少在此处显示的代码中没有。< / p>