说我有几个这样的基本对象:
[Serializable] public class Base { public string Property1 { get; set; } public int Property2 { get; set; } } [Serializable] public class Sub: Base { public List<string> Property3 { get; set; } public Sub():base() { Property3 = new List<string>(); } }
我将它们像这样序列化:
Sub s = new Sub {Property1 = "subtest",Property2 = 1000}; s.Property3.Add("item 1"); s.Property3.Add("item 2"); XmlSerializer sFormater = new XmlSerializer(typeof(Sub)); using (FileStream fStream = new FileStream("SubData.xml",FileMode.Create,FileAccess.Write,FileShare.None)) { sFormater.Serialize(fStream,s); }
我如何反序列化他们,以便我回到正确的班级?
像我一样,我想要这样的东西
XmlSerializer bFormater = new XmlSerializer(typeof (Base)); Base newBase; using (FileStream fStream = new FileStream("BaseData.xml",FileMode.Open,FileAccess.Read,FileShare.Read)) { newBase = (Base) bFormater.Deserialize(fStream); }
除了我可以传递任何从Base下降的类的XML文件,并且将创建正确的类.
我想我可以读取XML的根节点的名称,并使用switch语句创建正确的XmlSerializer,但是我想知道是否有一个更简单的方法.