序列化方法不按预期顺序调用

时间:2012-07-05 22:42:50

标签: c# serialization

我有以下设置:

[Serializable]
public class TickerSymbol : ISerializable
{
    public readonly string Symbol;

    public TickerSymbol(string Symbol)
    {
        this.Symbol = Symbol;
    }

    protected TickerSymbol(SerializationInfo info, StreamingContext context)
    {
        // Call Order: 3
        Symbol = info.GetString("Symbol");
    }

    public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        info.AddValue<string>("Symbol", Symbol);
    }

    [OnDeserialized]
    public void OnDeserialized(StreamingContext context)
    {
        // Call Order: 1
        // Do something that requires the symbol to not be null
    }
}

[Serializable]
public class EquitySymbol : TickerSymbol, ISerializable
{
    public EquitySymbol(stirng Symbol)
        : base(Symbol)
    {
    }

    protected EquitySymbol(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {
        // Call Order: 4
    }

    public override void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        base.GetObjectData(info, context);
    }

    [OnDeserialized]
    public void OnDeserialized(StreamingContext context)
    {
        // Call order 2
    }
}

我原本希望在相应的序列化构造函数之后调用标记为[OnDeserialized]的方法,但看起来它们被称为BEFORE的序列化构造函数 - 这应该如何工作?

威廉

1 个答案:

答案 0 :(得分:1)

可能的解决方案可能是使Symbol成为属性而不是字段。然后,可以在Symbol的setter中执行所需的操作,例如:

private string _symbol;

public string Symbol {
    get { return _symbol; }
    set { 
        _symbol = value;
        if (_symbol != null ) {
            // here the _symbol is right after deserialization,
            // and it is certainly not null
        }
    }
}

此外,通常不建议在.NET中公开公共字段,因为这些字段通常被认为是实现细节,而不是接口构造;有关更多信息,请参阅以下资源:

Why won't anyone accept public fields in C#? - 关于StackOverflow的精彩讨论

CA1051: Do not declare visible instance fields http://msdn.microsoft.com/en-us/library/ms182141.aspx - 微软对此问题的解释