如何在DataContractSerializer之后初始化私有字段

本文关键字:字段 初始化 之后 DataContractSerializer | 更新日期: 2023-09-27 18:20:04

我知道你可以用DataContractSerializer序列化私有字段,但我只想保存最少量的易于人工编辑的数据。在DataContractSerializer完成它的工作后,是否有一个函数可以在DataContract序列化程序类中重写或设置,该函数只在它完成反序列化后设置私有字段?

[DataContract()]
[KnownType(typeof(stateCom))]
[KnownType(typeof(stateIp))]
abstract public  class  state
{
    [DataMember()]
    public string tag;
    [DataMember()]
    public byte Id;
    public HandleConnection master;

    // default data contstructor for xml serialization
    public state()
    {
    }
    public abstract void openPort();

    public abstract void closePort();
}

如何在DataContractSerializer之后初始化私有字段

您可以在类中创建例如OnDeserialized方法,并将OnDeserializedAttribute应用于它,例如:

[DataContract()]
[KnownType(typeof(stateCom))]
[KnownType(typeof(stateIp))]
abstract public  class  state
{
    [DataMember()]
    public string tag;
    [DataMember()]
    public byte Id;
    public HandleConnection master;

    // default data contstructor for xml serialization
    public state()
    {
    }
    public abstract void openPort();

    public abstract void closePort();
    [OnDeserialized]
    internal void OnDeserialized(StreamingContext context)
    {
        // this is called after deserialization
    }
}