对象未在OnDeserialized

时间:2017-10-20 22:17:59

标签: c# deserialization

我有两个班级:

[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(),一切正常。但是,我需要在某个时候运行该方法。

0 个答案:

没有答案