在C#中序列化对象时格式化日期(2.0)
问题描述:
我使用大量属性对对象进行了xml序列化,并且我有两个带有DateTime类型的属性。我想格式化序列化输出的日期。我真的不想实现IXmlSerializable接口并覆盖每个属性的序列化。有没有其他方法可以实现这一点?在C#中序列化对象时格式化日期(2.0)
(我正在使用C#,.NET 2)
谢谢。
答
对于XML序列化,你将不得不实施IXmlSerializable
,而不是ISerializable
。
但是,您可以通过使用帮助器属性并使用XmlIgnore
属性标记DateTime
属性来解决此问题。
public class Foo
{
[XmlIgnore]
public DateTime Bar { get; set; }
public string BarFormatted
{
get { return this.Bar.ToString("dd-MM-yyyy"); }
set { this.Bar = DateTime.ParseExact(value, "dd-MM-yyyy", null); }
}
}
答
您可以使用包装类/结构DateTime
覆盖ToString
方法。
public struct CustomDateTime
{
private readonly DateTime _date;
public CustomDateTime(DateTime date)
{
_date = date;
}
public override string ToString()
{
return _date.ToString("custom format");
}
}
是的,这是IXmlSerializable - 正在输入急... - 更正。谢谢。 – Zoman 2010-06-03 10:29:59