C#中將xml檔案反序列化為例項時採用基類還是派生類的知識點討論
阿新 • • 發佈:2020-01-07
基類:
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檔案的根節點的名字與被反序列化的類的名字一致即可。當然了,反序列化成功後,用基類的例項引用去指向反序列化後的派生類的例項也是沒問題的。
其它注意事項:
如果在一個類中有靜態的成員變數,則在該類呼叫建構函式例項化之前,會首先例項化靜態的成員變數。
以上就是本次介紹的全部知識點內容,感謝大家的學習和對我們的支援。