我有两个班级:
[Serializable]
class AddressBook {
private Dictionary<string, Address> entries = new Dictionary<string, Address>();
[OnDeserialized]
private void EnsureValid(StreamingContext context) {
// make sure each entry has a non-whitespace name and non-null address
}
}
[Serializable]
class Address {
private Dictionary<string, string> elements = new Dictionary<string, string>();
public IReadOnlyList<string> StandardElements { get; } = new List<string> { "street", "city", "state", "zip" };
[OnDeserialized]
private void EnsureValid(StreamingContext context) {
foreach (var standardElement in StandardElements) {
if (!elements.ContainsKey(standardElement) || elements[standardElement] == null) {
elements[standardElement] = String.Empty;
}
}
}
}
这是我的反序列化代码:
public AddressBook Load() {
var formatter = new BinaryFormatter();
using (var input = File.OpenRead(path))
{
return (AddressBook)formatter.Deserialize(input);
}
}
AddressBook
反序列化很好,但当Address
AddressBook
字段中包含的entries
个实例反序列化并且Address.EnsureValid()
运行elements
时是null
。我原以为在OnDeserialized
方法运行时会完全创建对象实例。我错过了什么吗?
如果我在[OnDeserialized]
中注释Address.EnsureValid()
,一切正常。但是,我需要在某个时候运行该方法。