我正在对一个具有大量属性的对象进行XML序列化,其中有两个DateTime类型的属性。我想要格式化序列化输出中的日期。我不想为每个属性实现IXmlSerializable接口并覆盖序列化。有没有其他方法可以做到这一点?
(我使用C#,.NET 2)
谢谢。
我正在对一个具有大量属性的对象进行XML序列化,其中有两个DateTime类型的属性。我想要格式化序列化输出中的日期。我不想为每个属性实现IXmlSerializable接口并覆盖序列化。有没有其他方法可以做到这一点?
(我使用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");
}
}