我是靠谱客的博主 醉熏小松鼠,这篇文章主要介绍C#中将xml文件反序列化为实例时采用基类还是派生类的知识点讨论,现在分享给大家,希望可以做个参考。

基类:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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; } } } }

派生类:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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; } } } }

主函数调用测试代码为:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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:MyProjectDeserializeTestDeserializeTestbinDebugGobalConfigSettingsBase.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:MyProjectDeserializeTestDeserializeTestbinDebugGobalConfigWorldWind.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文件:

复制代码
1
2
3
4
<?xml version="1.0" encoding="utf-8"?> <SettingsBase> <FileName>WorldWind.xml</FileName> </SettingsBase>

派生类的XML文件:

复制代码
1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?> <WorldWindSettings> <FileName>WorldWind.xml</FileName> <ProxyUrl>www.baidu.com</ProxyUrl> </WorldWindSettings>

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

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

其它注意事项:

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

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

最后

以上就是醉熏小松鼠最近收集整理的关于C#中将xml文件反序列化为实例时采用基类还是派生类的知识点讨论的全部内容,更多相关C#中将xml文件反序列化为实例时采用基类还是派生类内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(156)

评论列表共有 0 条评论

立即
投稿
返回
顶部