软件编程
位置:首页>> 软件编程>> C#编程>> C#中将xml文件反序列化为实例时采用基类还是派生类的知识点讨论

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

作者:rainbow70626  发布时间:2022-08-04 19:27:32 

标签:C#,xml,反序列化

基类:


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文件的根节点的名字与被反序列化的类的名字一致即可。当然了,反序列化成功后,用基类的实例引用去指向反序列化后的派生类的实例也是没问题的。

其它注意事项:

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

来源:https://www.cnblogs.com/rainbow70626/p/11839330.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com