如何序列化DateTimeFormatInfo类型的对象?

时间:2014-04-14 15:15:05

标签: c# serialization xml-serialization 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 类型   使用 XmlInclude SoapInclude 属性指定静态未知的类型。

我需要添加什么来序列化DateTimeFormatInfo吗?

1 个答案:

答案 0 :(得分:0)

您需要在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);