加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

.NET如何将TimeSpan序列化为XML(不是同一个问题!)

发布时间:2020-12-16 22:55:05 所属栏目:百科 来源:网络整理
导读:我的问题是 How to serialize a TimeSpan to XML的延续 我有许多DTO对象传递TimeSpan实例.使用原始帖子中描述的hack有效,但它要求我在每个DTO中为每个TimeSpan属性重复相同的代码. 所以,我带来了以下包装类,它是XML可序列化的就好了: #if !SILVERLIGHT[Seri
我的问题是 How to serialize a TimeSpan to XML的延续

我有许多DTO对象传递TimeSpan实例.使用原始帖子中描述的hack有效,但它要求我在每个DTO中为每个TimeSpan属性重复相同的代码.

所以,我带来了以下包装类,它是XML可序列化的就好了:

#if !SILVERLIGHT
[Serializable]
#endif
[DataContract]
public class TimeSpanWrapper
{
  [DataMember(Order = 1)]
  [XmlIgnore]
  public TimeSpan Value { get; set; }

  public static implicit operator TimeSpan?(TimeSpanWrapper o)
  {
    return o == null ? default(TimeSpan?) : o.Value;
  }

  public static implicit operator TimeSpanWrapper(TimeSpan? o)
  {
    return o == null ? null : new TimeSpanWrapper { Value = o.Value };
  }

  public static implicit operator TimeSpan(TimeSpanWrapper o)
  {
    return o == null ? default(TimeSpan) : o.Value;
  }

  public static implicit operator TimeSpanWrapper(TimeSpan o)
  {
    return o == default(TimeSpan) ? null : new TimeSpanWrapper { Value = o };
  }

  [JsonIgnore]
  [XmlElement("Value")]
  [Browsable(false),EditorBrowsable(EditorBrowsableState.Never)]
  public long ValueMilliSeconds
  {
    get { return Value.Ticks / 10000; }
    set { Value = new TimeSpan(value * 10000); }
  }
}

问题是它产生的XML看起来像这样:

<Duration>
  <Value>20000</Value>
</Duration>

而不是自然

<Duration>20000</Duration>

我的问题是,我可以“吃蛋糕,吃完全”吗?意思是,享受所描述的hack而不会使用相同的重复代码混乱所有DTO并且具有自然的外观XML?

谢谢.

解决方法

将[XmlElement(“Value”)]更改为[XmlText].然后,如果你序列化这样的事情:

[Serializable]
public class TestEntity
{
    public string Name { get; set; }
    public TimeSpanWrapper Time { get; set; }
}

你会得到这样的XML:

<TestEntity>
    <Name>Hello</Name>
    <Time>3723000</Time>
</TestEntity>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读