在C#(2.0)中序列化对象时如何格式化日期

3

我正在对一个具有大量属性的对象进行XML序列化,其中有两个DateTime类型的属性。我想要格式化序列化输出中的日期。我不想为每个属性实现IXmlSerializable接口并覆盖序列化。有没有其他方法可以做到这一点?

(我使用C#,.NET 2)

谢谢。

2个回答

5

如果要进行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); }
    }
}

是的,它是IXmlSerializable - 我匆忙打字... - 已经更正了。谢谢。 - Zoman

1
你可以使用一个包装类或结构体来处理 DateTime,并重写它的ToString方法。
public struct CustomDateTime
{
    private readonly DateTime _date;

    public CustomDateTime(DateTime date)
    {
        _date = date;
    }

    public override string ToString()
    {
        return _date.ToString("custom format");
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接