如何将 TimeSpan 序列化为 XML [英] How to serialize a TimeSpan to XML
问题描述
我正在尝试将 .NET TimeSpan
对象序列化为 XML,但它不起作用.一个快速的谷歌建议虽然 TimeSpan
是可序列化的,但 XmlCustomFormatter
不提供将 TimeSpan
对象转换为 XML 或从 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
,而是序列化TimeSpan.Ticks
的结果(并使用new 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 或从 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)]
这只是将它隐藏在 UI 和引用 dll 中,以避免混淆.
This just hides it in the UI and in referencing dlls, to avoid confusion.
这篇关于如何将 TimeSpan 序列化为 XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!