.NET(C#):XML序列化时派生类的处理
.NET(C#):XML序列化时派生类的处理
针对基类的XmlSerializer序列化派生类
第一种方法是在基类添加XmlInclude特性,这样的话基类的XmlSerializer可以序列化派生类了。
1 [XmlInclude(typeof(B))] 2 public class A 3 { 4 public int value; 5 } 6 public class B: A 7 { 8 public int valueB; 9 } 10 11 class Program 12 { 13 static void Main() 14 { 15 var xs =new XmlSerializer(typeof(A)); 16 using (var textWriter =new StringWriter()) 17 { 18 xs.Serialize(textWriter, new B()); 19 Console.WriteLine(textWriter); 20 } 21 } 22 }
第二种方法就是在XmlSerializer的构造函数内指定派生类型,然后序列化,这样就不用在基类上加入XmlInclude特性了。
1 public class A 2 { 3 public int value; 4 } 5 public class B: A 6 { 7 public int valueB; 8 } 9 10 class Program 11 { 12 static void Main() 13 { 14 var xs =new XmlSerializer(typeof(A), new Type[] { typeof(B) }); 15 using (var textWriter =new StringWriter()) 16 { 17 xs.Serialize(textWriter, new B()); 18 Console.WriteLine(textWriter); 19 } 20 } 21 }