![](/img/trans.png)
[英]C/C++ DLL failing after .NET framework upgrade from 3.5 to 4.6
[英]XmlSerializer errors after updating from .NET 3.5 to .NET 4.6
所以我最近將一個項目從 .NET 3.5 更新到了 .NET 4.6 並且我的 XML 序列化停止工作。 我把它縮小到一個單一的結構,我同意,它看起來很奇怪。
[XmlElement("price1", typeof(PriceBonusData))]
[XmlElement("price2", typeof(PriceBonusData))]
public List<PriceBonusData> PriceBonusDataList;
報錯說我需要給這個字段添加XmlChoiceIdentifier
屬性,但是不管我怎么添加,還是不行。 奇怪的是,它確實適用於 .NET 3.5,那么為什么突然需要新屬性呢?
編輯:這是我嘗試使用 XmlChoiceIdentifier。 我在文檔和 SO 上都看到了類似的解決方案,但它似乎對我不起作用。
[XmlElement(IsNullable = false)]
[XmlIgnore]
public ItemChoiceType[] ItemTypeArray = (ItemChoiceType[])Enum.GetValues(typeof(ItemChoiceType));
[XmlChoiceIdentifier("ItemTypeArray")]
[XmlElement("price1", typeof(PriceBonusData))]
[XmlElement("price2", typeof(PriceBonusData))]
public List<PriceBonusData> PriceBonusDataList;
[XmlType(IncludeInSchema = false)]
public enum ItemChoiceType
{
[XmlEnum("price1")]
price1,
[XmlEnum("price2")]
price2
}
Edit2:我使用 .NET 3.5 版本在一個空項目上運行了一些進一步的測試,所以我想我可以分享它在工作時的行為方式。
此結構使用最后一個 XmlElement(在本例中為“price2”)進行序列化。
在反序列化期間,兩個元素都是有效的。 我手動更改了 XML 文件,使其同時包含“price1”和“price2”,並正確反序列化它們。
如果您只是想反序列化,那么這可能對您有用:
public class Foo
{
// the "real" list that takes <price1> elements
[XmlElement("price1", typeof(PriceBonusData))]
public List<PriceBonusData> PriceBonusDataList {get;} = new List<PriceBonusData>();
// spoof a second list that handles <price2> elements (actually: the same list)
[XmlElement("price2", typeof(PriceBonusData))]
public List<PriceBonusData> PriceBonusDataList2 => PriceBonusDataList;
// this disables serialization of PriceBonusDataList2 so we don't double up
public bool ShouldSerializePriceBonusDataList2() => false;
}
缺點是,如果你序列化,一切都將變得<price1>
無論它開始作為一個<price1>
或<price2>
...但是...我看不到周圍的任何方式,因為沒有什么地方存儲它原來的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.