欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中将xml文件反序列化为实例时采用基类还是派生类的知识点讨论

程序员文章站 2023-10-31 13:27:52
基类: using system; using system.collections.generic; using system.linq; using system....

基类:

using system;
using system.collections.generic;
using system.linq;
using system.text;

namespace deserializetest
{
 public class settingsbase
 {
 private string m_filename;

 public string filename 
 {
  get { return m_filename; }
  set { m_filename = value; }
 }
  
 }
}

派生类:

using system;
using system.collections.generic;
using system.linq;
using system.text;

namespace deserializetest
{
 public class worldwindsettings : settingsbase
 {
  public worldwindsettings()
   : base()
  {
  }


  private string m_proxyurl = "";

  public string proxyurl
  {
   get
   {
    return m_proxyurl;
   }
   set
   {
    this.m_proxyurl = value;
   }
  }
 }
}

主函数调用测试代码为:

using system;
using system.collections.generic;
using system.linq;
using system.text;

using system.io;
using system.xml.serialization;

namespace deserializetest
{
 class program
 {
  static void main(string[] args)
  {
   //测试1:测试将xml文件反序列化为基类实例。测试通过。只要xml文件的根节点的名字与被反序列化的类的名字一致即可
   string filenamebase = @"d:\myproject\deserializetest\deserializetest\bin\debug\gobalconfig\settingsbase.xml";
   settingsbase settingsbase;
   xmlserializer serbase = new xmlserializer(typeof(settingsbase));
   using (textreader trbase = new streamreader(filenamebase))
   {
    settingsbase = (settingsbase)serbase.deserialize(trbase);
    settingsbase.filename = filenamebase;
   }

   //测试2:测试将xml文件反序列化为子类实例。测试通过。只要xml文件的根节点的名字与被反序列化的类的名字一致即可。当然了,用基类的实例引用去指向反序列化后的派生类的实例也是没问题的。
   string filename = @"d:\myproject\deserializetest\deserializetest\bin\debug\gobalconfig\worldwind.xml";
   settingsbase settings;//当前了此处定义为worldwindsettings settings;也没问题
   type type = typeof(worldwindsettings);//因为xml文件的根节点名称是worldwindsettings,此处只能为worldwindsettings,而不能为settingsbase
   xmlserializer ser = new xmlserializer(type);
   using (textreader tr = new streamreader(filename))
   {
    //settings = (worldwindsettings)ser.deserialize(tr);//这两句代码都可以通过!
    settings = (settingsbase)ser.deserialize(tr);
    settings.filename = filename;
   }

   system.console.writeline("hello");
  }
 }
}

基类的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<settingsbase>
 <filename>worldwind.xml</filename>
</settingsbase>

派生类的xml文件:

<?xml version="1.0" encoding="utf-8"?>
<worldwindsettings>
 <filename>worldwind.xml</filename>
 <proxyurl>www.baidu.com</proxyurl>
</worldwindsettings>

源码下载:deserializetest.rar 提取码:djpe

总结:将xml文件反序列化为类的实例的时候,只要xml文件的根节点的名字与被反序列化的类的名字一致即可。当然了,反序列化成功后,用基类的实例引用去指向反序列化后的派生类的实例也是没问题的。

其它注意事项:

如果在一个类中有静态的成员变量,则在该类调用构造函数实例化之前,会首先实例化静态的成员变量。

以上就是本次介绍的全部知识点内容,感谢大家的学习和对的支持。