我可以序列化一个列表真的很容易:
List<String> fieldsToNotCopy =new List<String> {"Iteration Path","Iteration ID"}; fieldsToNotCopy.SerializeObject("FieldsToNotMove.xml");
现在我需要一个这样的方法:
List<String> loadedList = new List<String(); loadedList.DeserializeObject("FieldsToNotMove.xml");
有没有这样的方法?或者我需要创建一个XML读取器并以这种方式加载它?
编辑:结果没有内置的SerialzeObject.我曾经在我的项目中做了一个,忘了它.当我发现它,我以为它是内置的.如果你好奇,这是我做的SerializeObject:
// Save an object out to the disk public static void SerializeObject<T>(this T toSerialize,String filename) { XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType()); TextWriter textWriter = new StreamWriter(filename); xmlSerializer.Serialize(textWriter,toSerialize); textWriter.Close(); }
解决方法
没有像SerializeObject这样的内置方法,但是编码一个不是很难.
public void SerializeObject(this List<string> list,string fileName) { var serializer = new XmlSerializer(typeof(List<string>)); using ( var stream = File.OpenWrite(fileName)) { serializer.Serialize(stream,list); } }
反序列化
public void Deserialize(this List<string> list,string fileName) { var serializer = new XmlSerializer(typeof(List<string>)); using ( var stream = File.OpenRead(fileName) ){ var other = (List<string>)(serializer.Deserialize(stream)); list.Clear(); list.AddRange(other); } }