【问题标题】:How to serialize the object of type DateTimeFormatInfo?如何序列化 DateTimeFormatInfo 类型的对象?
【发布时间】:2014-04-14 15:15:04
【问题描述】:

我想序列化 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 吗?

【问题讨论】:

  • 序列化程序将遍历可能包含不可序列化对象的对象图。我建议改为序列化日期模式。

标签: c# serialization xml-serialization datetimeformatinfo


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 2011-02-17
    • 1970-01-01
    • 2016-05-15
    • 2020-12-25
    • 2012-01-29
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    相关资源
    最近更新 更多