问题是反序列化时我在存储库中得到零计数(没有任何错误)
[Serializable]
class RegexRepository : Dictionary<string, string>
{
public RegexRepository()
{
//this.Add("All", "ALL");
//this.Add("Name", @"Name:(?<data>[\s\w]+)Email");
//this.Add("Email", @"Email:(?<data>[\w\s@]+\.com)");
//this.Add("Phone Number", "Phone:(?<data>\\d+)");
}
protected RegexRepository(SerializationInfo info, StreamingContext context)
{
}
private static RegexRepository repo = new RegexRepository();
public static RegexRepository Instance
{
get
{
if (repo == null)
{
repo = new RegexRepository();
}
return repo;
}
}
string FileName = AppDomain.CurrentDomain.BaseDirectory + "BinaryFile.dat";
public void Serialize()
{
using (FileStream ms = new FileStream(FileName, FileMode.OpenOrCreate))
{
var bf = new BinaryFormatter();
bf.Serialize(ms, this);
}
}
public void Deserialize()
{
if (System.IO.File.Exists(FileName))
{
using (FileStream ms = new FileStream(FileName, FileMode.Open))
{
var bf = new BinaryFormatter();
repo = (RegexRepository)bf.Deserialize(ms);
//Here i get zero count in repo, checked while debugging
}
}
}
}
我已经看到BinaryFile.dat不为空,我可以在其中看到一些记录。请帮助我
最佳答案
您需要从流式构造函数中调用基本构造函数:
protected RegexRepository(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
此外,FileName
可能不应该是一个字段,您在类中为其分配内存,这是没有必要的。相反,静态属性似乎更有意义:
static string FileName
{
get
{
return AppDomain.CurrentDomain.BaseDirectory + "BinaryFile.dat";
}
}
关于c# - 反序列化返回空对象,使用Filestream和Binaryformatter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33623701/