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    提取码:pkya 

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

posted @ 2019-11-12 00:19  rainbow70626  阅读(544)  评论(0编辑  收藏  举报