我正在序列化DateTimeFormatInfo,并在反序列化时收到异常“不是给定区域性的有效日历”。从检查
.net source
问:我序列化/反序列化是错误的,还是这是一个bug?
4.7.2中要重新编程的源:
using System;
using System.Globalization;
using System.IO;
public static class Module1
{
public static void Main()
{
System.Globalization.CultureInfo currentCulture;
currentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
// currentCulture.OptionalCalendars includes Localized and USEnglish
currentCulture.DateTimeFormat.Calendar = new GregorianCalendar(GregorianCalendarTypes.USEnglish);
System.Xml.Serialization.XmlSerializer x;
x = new System.Xml.Serialization.XmlSerializer(typeof(DateTimeFormatInfo), new[] { typeof(GregorianCalendar) });
// Serialize
string xml;
using (MemoryStream writer = new MemoryStream())
{
x.Serialize(writer, currentCulture.DateTimeFormat);
writer.Position = 0;
using (var reader = new StreamReader(writer))
{
xml = reader.ReadToEnd();
} // reader
} // writer
// Deserialize
using (StringReader stringReader = new StringReader(xml))
{
// This will throw an exception because the invariant culture which was used in the parameterless constructor doesn't have USEnglish in OptionalCalendars
x.Deserialize(stringReader);
} // stringReader
Console.WriteLine("ok");
}
}
这是一个
fiddle