Default Values For Missing Data Members In DataContractSerializer

你离开我真会死。 提交于 2020-01-14 12:18:51

问题


With the below two data members in a DataContract then using a DataContractSerializer, only Name is serialized as expected. My problem is when I deserialize the file. "Name" is read and loaded properly but as "Timeout" does not exist I would expect it to stay at the default of "TimeSpan.FromHours(12)". What infact happens is the DataContractSerializer assigns a value but as it has no value to assign it uses the timespan default of 0. Is there anyway around this behavour?

private string _name;
    [DataMember(Name = "Name")]
    public string Name
    {
        get
        {
            return _name;
        }
        set
        {
            _name= value;
        }
    }

    private TimeSpan _timeout = TimeSpan.FromHours(12);
    public TimeSpan Timeout
    {
        get
        {
            return _timeout ;
        }
        set
        {
            _timeout = value;
        }
    }

回答1:


Is this your answer then

using OnDeserialized

[OnDeserialized]
void OnDeserialized(StreamingContext context)
{
    this._timeout = TimeSpan.FromHours(12);
}

from here Setting the initial value of a property when using DataContractSerializer



来源:https://stackoverflow.com/questions/11417436/default-values-for-missing-data-members-in-datacontractserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!