2010-06-03 149 views
3

我使用大量屬性對對象進行了xml序列化,並且我有兩個帶有DateTime類型的屬性。我想格式化序列化輸出的日期。我真的不想實現IXmlSerializable接口並覆蓋每個屬性的序列化。有沒有其他方法可以實現這一點?在C#中序列化對象時格式化日期(2.0)

(我正在使用C#,.NET 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); } 
    } 
} 
+0

是的,這是IXmlSerializable - 正在輸入急... - 更正。謝謝。 – Zoman 2010-06-03 10:29:59

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