我在 XmlSerializer 中发现了一些意外行为。如果您对列表具有默认构造函数的对象列表进行脱轨,则该列表也会被附加。
任何人都知道如何解决这个问题?这是一个例子。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;
namespace XmlSerialiserTest
{
public class Schedule
{
public Schedule()
{
Days = new List<DayOfWeek>() { DayOfWeek.Monday };
Time = DateTime.UtcNow;
}
public List<DayOfWeek> Days { get; set; }
public DateTime Time { get; set; }
public override string ToString()
{
return String.Format("{0},{1}", Time.ToShortTimeString(), string.Join(",", Days));
}
}
public class Schedules
{
public List<Schedule> ScheduleList { get; set; }
public Schedules()
{
ScheduleList = new List<Schedule>();
}
public override string ToString()
{
return string.Join(":",ScheduleList);
}
}
class Program
{
static void Main(string[] args)
{
// create a our list of Schedule with one schedule in
// default constructor will give us Monday by default
Schedules schedulesOut = new Schedules();
schedulesOut.ScheduleList.Add(new Schedule());
// Save
XmlSerializer s = new XmlSerializer(typeof(Schedules));
TextWriter writer = new StreamWriter("C:\\xmltest.xml");
s.Serialize(writer,schedulesOut);
writer.Close();
Console.WriteLine(schedulesOut);
// Output is 15:09,Monday
// Now saved to disk and read back
TextReader reader = new StreamReader("C:\\xmltest.xml");
Schedules schedulesIn = (Schedules)s.Deserialize(reader);
Console.WriteLine(schedulesIn);
// Output is 15:09,Monday,Monday
// schedulesIn in now contains two Mondays ,not one as expected
}
}
}