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

时间:2012-01-12 17:57:24

标签: c# xml-serialization datacontractserializer

我知道您可以使用DataContractSerializer序列化私有字段,但我只想保存易于人工编辑的最少量数据。在DataContractSerializer完成之后,我可以在DataContractSerializer类中覆盖或设置一个函数,它只是在完成反序列化后设置私有字段吗?

[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();
}

1 个答案:

答案 0 :(得分:2)

您可以创建例如您班级中的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
    }
}