DataContractSerializer

DataContractSerializer

本文介绍了DataContractSerializer中缺少数据成员的默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在DataContract中使用以下两个数据成员,然后使用DataContractSerializer,仅Name会按预期序列化.我的问题是当我反序列化文件时.已正确读取并加载了名称",但由于不存在超时",我希望它保持默认值"TimeSpan.FromHours(12)".实际上发生的是DataContractSerializer分配了一个值,但是由于没有值可分配,因此使用默认的时间跨度0.反正是这种行为吗?

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;
        }
    }

推荐答案

那么这是你的答案

使用OnDeserialized

using OnDeserialized

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

从此处设置属性的初始值使用DataContractSerializer时

这篇关于DataContractSerializer中缺少数据成员的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 23:59