问题
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