开发者

Formatting dates when serialising an object in C# (2.0)

I'm xml-serializing a object with a large number of properties and I have two properties with DateTime types. I'd like to format the dates for the serialized output. I don't really want to impl开发者_StackOverflow社区ement the IXmlSerializable interface and overwrite the serialization for every property. Is there any other way to achieve this?

(I'm using C#, .NET 2)

Thanks.


For XML serialization you would have to implement IXmlSerializable and not ISerializable.

However you can workaround this by using a helper property and by marking the DateTime properties with the XmlIgnore attribute.

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); }
    }
}


You can use a wrapper class/struct for DateTime that overrides ToString method.

public struct CustomDateTime
{
    private readonly DateTime _date;

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜