簡體   English   中英

如何序列化DateTimeFormatInfo類型的對象?

[英]How to serialize the object of type DateTimeFormatInfo?

我想序列化DatetimeFormatInfo類型的對象。

我嘗試了以下代碼:

DateTimeFormatInfo dateTimeFormat = new DateTimeFormatInfo();
dateTimeFormat.ShortDatePattern = "dd-MMM-yy";
xs = new XmlSerializer(dateTimeFormat.GetType());
StreamWriter sw = new StreamWriter("Setting.xml");
xs.Serialize(sw, dateTimeFormat);

但這引發了以下異常。

未處理System.InvalidOperationException
生成XML文檔時出錯。
不應使用System.Globalization.GregorianCalendar類型。
使用XmlIncludeSoapInclude屬性可以指定靜態未知的類型。

我需要添加什么來序列化DateTimeFormatInfo嗎?

您需要在XmlSerializer包含要序列化的成癮對象類型的列表。 在您的情況下,您需要添加對象類型System.Globalization.GregorianCalendar

        System.Globalization.DateTimeFormatInfo dateTimeFormat = new System.Globalization.DateTimeFormatInfo();
        dateTimeFormat.ShortDatePattern = "dd-MMM-yy";

        // Add here all the extra types you need to serialize
        Type[] extraTypes = new Type[] { typeof(System.Globalization.GregorianCalendar) };

        System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(dateTimeFormat.GetType(), extraTypes);
        System.IO.StreamWriter sw = new System.IO.StreamWriter(@"c:\testso.xml");
        xs.Serialize(sw, dateTimeFormat);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM