1
我想我終於明白了XmlSerialization,但是我最後的方法讓我覺得它就像一個新手。 我的意圖是創建一個序列化和反序列化某種配置的框架。所以我創建了一個配置類如下:反序列化派生類型
/// <summary>
/// Application-wide configurations that determine how to transform the features.
/// </summary>
[XmlRoot(Namespace = "baseNS")]
public class Config
{
/// <summary>
/// List of all configuration-settings of this application
/// </summary>
[System.Xml.Serialization.XmlElement("Setting")]
public List<Setting> Settings = new List<Setting>();
}
現在我需要某種配置,它定義了一個自定義設置列表。
/// <summary>
/// Application-wide configurations that determine how to transform the features.
/// </summary>
[System.Xml.Serialization.XmlRoot("Config", Namespace = "baseNS")]
[System.Xml.Serialization.XmlInclude(typeof(BW_Setting))]
public class BW_Config : Config {
// nothing to add, only needed to include type BW_Setting
}
/// <summary>
/// Provides settings for one single type of source-feature specified by the <see cref="CQLQuery"/>-property. Only one target-featureType is possible for every setting.
/// However settings for different targetTypes may have the same source-type provided.
/// </summary>
[System.Xml.Serialization.XmlRoot("Setting", Namespace = "anotherNS")]
public class BW_Setting : Setting {
// add and modify some attributes
}
據我所知,我在基類(設置)上放置了XmlInclude屬性。因此設置和BW_Setting駐留在不同的程序集中,後者取決於前者我不能使用這種方法,因爲我會得到一個圓形引用。
這是實際的串行代碼:
XmlSerializer ser = new XmlSerializer(typeof(BW_Config));
BW_Config c = new BW_Config();
c.Settings.Add(new BW_Setting());
((BW_Setting)c.Settings[0]).CQLQuery = "test";
現在執行上面時,我得到錯誤"Type BW_Setting was not expected. Use XmlInclude..."
我可以更改自定義組件中的一切,但因此基地之一屬於框架我不能更改。你能幫我做序列化(和反序列化)嗎?