如何序列化一个时间跨度为XML [英] How to serialize a TimeSpan to XML

查看:132
本文介绍了如何序列化一个时间跨度为XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图序列化.NET 时间跨度对象到XML,这是行不通的。快速谷歌建议,而时间跨度是序列化时, XmlCustomFormatter 不提供方法,将时间跨度对象和XML。

I am trying to serialize a .NET TimeSpan object to XML and it is not working. A quick google has suggested that while TimeSpan is serializable, the XmlCustomFormatter does not provide methods to convert TimeSpan objects to and from XML.

一个建议的方法是忽略时间跨度系列化,而是连载 TimeSpan.Ticks 的结果(并使用新的时间跨度(蜱)反序列化)。这样的一个例子如下:

One suggested approach was to ignore the TimeSpan for serialization, and instead serialize the result of TimeSpan.Ticks (and use new TimeSpan(ticks) for deserialization). An example of this follows:

[Serializable]
public class MyClass
{
    // Local Variable
    private TimeSpan m_TimeSinceLastEvent;

    // Public Property - XmlIgnore as it doesn't serialize anyway
    [XmlIgnore]
    public TimeSpan TimeSinceLastEvent
    {
        get { return m_TimeSinceLastEvent; }
        set { m_TimeSinceLastEvent = value; }
    }

    // Pretend property for serialization
    [XmlElement("TimeSinceLastEvent")]
    public long TimeSinceLastEventTicks
    {
        get { return m_TimeSinceLastEvent.Ticks; }
        set { m_TimeSinceLastEvent = new TimeSpan(value); }
    }
}

虽然这会出现在我简短的测试工作 - 这是实现这一目标的最佳途径。

While this appears to work in my brief testing - is this the best way to achieve this?

有没有更好的方式来序列化的TimeSpan与XML?

Is there a better way to serialize a TimeSpan to and from XML?

推荐答案

您已经发布的方法可能是最干净的。如果你不喜欢额外的属性,你可以实现的IXmlSerializable ,但你必须做的所有,这在很大程度上违背了点。我会愉快地使用你张贴的方式;它是(例如)高效(无复杂的分析等),独立的文化,毫不含糊,和时间戳型号码容易且通常理解

The way you've already posted is probably the cleanest. If you don't like the extra property, you could implement IXmlSerializable, but then you have to do everything, which largely defeats the point. I'd happily use the approach you've posted; it is (for example) efficient (no complex parsing etc), culture independent, unambiguous, and timestamp-type numbers are easily and commonly understood.

顺便说一句,我经常补充:

As an aside, I often add:

[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]

这只是隐藏它在用户界面和引用的DLL,以避免混淆。

This just hides it in the UI and in referencing dlls, to avoid confusion.

这篇关于如何序列化一个时间跨度为XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆