C# - 如何将XML反序列化对象本身? [英] C# - How to xml deserialize object itself?
问题描述
public class Options
{
public FolderOption FolderOption { set; get; }
public Options()
{
FolderOption = new FolderOption();
}
public void Save()
{
XmlSerializer serializer = new XmlSerializer(typeof(Options));
TextWriter textWriter = new StreamWriter(@"C:\Options.xml");
serializer.Serialize(textWriter, this);
textWriter.Close();
}
public void Read()
{
XmlSerializer deserializer = new XmlSerializer(typeof(Options));
TextReader textReader = new StreamReader(@"C:\Options.xml");
//this = (Options)deserializer.Deserialize(textReader);
textReader.Close();
}
}
}
我设法保存没有问题,FolderOption的所有成员都反序列化。但问题是怎么看它?该生产线 - 这// =(选项)deserializer.Deserialize(TextReader的);将无法工作。
I managed to Save without problem, all members of FolderOption are deserialized. But the problem is how to read it back? The line - //this = (Options)deserializer.Deserialize(textReader); won't work.
编辑:任何解决这个问题?我们可以实现不分配到这个相同的目的是什么?这就是反序列化对象的选项回选项。我懒物业做财产。在表演的最高水平将节省不少功夫的。
Any solution to this problem? Can we achieve the same purpose without assigning to this? That is deserialize Options object back into Option. I am lazy to do it property by property. Performing on the highest level would save of lot of effort.
推荐答案
如果您选择的类型是一个结构这将工作,因为你可以改变一个结构体本身。
This will work if your Options type is a struct, as you can a alter a struct itself.
如果选项是一个类(引用类型),你不能指定为引用类型的当前实例,在该实例。建议你写一个辅助类,并把你的读取和保存方法有,像这样
If Options is a class (reference type), you can't assign to the current instance of a reference type with in that instance. Suggesting you to write a helper class, and put your Read and Save methods there, like this
public class XmlSerializerHelper<T>
{
public Type _type;
public XmlSerializerHelper()
{
_type = typeof(T);
}
public void Save(string path, object obj)
{
using (TextWriter textWriter = new StreamWriter(path))
{
XmlSerializer serializer = new XmlSerializer(_type);
serializer.Serialize(textWriter, obj);
}
}
public T Read(string path)
{
T result;
using (TextReader textReader = new StreamReader(path))
{
XmlSerializer deserializer = new XmlSerializer(_type);
result = (T)deserializer.Deserialize(textReader);
}
return result;
}
}
然后使用它从你的来电者,阅读和保存,而不是从阶级尝试它的对象。
And then consume it from your caller, to read and save objects, instead of trying it from the class.
//In the caller
var helper=new XmlSerializerHelper<Options>();
var obj=new Options();
//Write and read
helper.Save("yourpath",obj);
obj=helper.Read("yourpath");
和把XmlSerializerHelper在你的Util的命名空间,它是可重复使用,可与任何类型的工作。
And put the XmlSerializerHelper in your Util's namespace, it is reusable and will work with any type.
这篇关于C# - 如何将XML反序列化对象本身?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!