[英]Serialize Abstract class with different attribute name
在導出流程上,我有一些XML元素表示相同的內容,但名稱不同。 我無法更改其他軟件定義的名稱。
我需要這樣的東西:
<class1>
<MY_FIELD></MY_FIELD>
</class1>
<class2>
<my_field></my_field>
</class2>
由於在兩個字段上需要進行的處理都是相同的,因此我想創建一個包含它的抽象類。
現在,這就是我所擁有的:
public abstract class MyAbstract
{
[XmlAttribute("MY_FIELD")]
public MyField {get;set;}
}
[Serializable]
public class Class1 : MyAbstract
{
}
[Serializable]
public class Class2 : MyAbstract
{
}
有沒有一種方法可以在最終類( class1
和class2
)上指定不同的XmlAttribute
,以便我可以在MyField
上設置屬性?
編輯 :我正在嘗試使用XmlAttributeOverrides
,這似乎做我想要的,但我不能使其工作。 我不知道我在想什么。
var myType = typeof(Class1);
var overrides = new XmlAttributeOverrides();
var attrs = new XmlAttributes
{
XmlAttribute = new XmlAttributeAttribute("test")
};
overrides.Add(myType, "MyField",attrs);
對於串行器
var serializer = new XmlSerializer(myType, overrides);
Edit2 :最后,我最終刪除了抽象類上的屬性,並在每個類上添加了吸氣劑以進行序列化。 這很糟糕,但我仍然希望有人能給我適當的選擇。
嘗試
public abstract class MyAbstract
{
abstract public MyField {get;set;}
}
[Serializable]
public class Class1 : MyAbstract
{
[XmlAttribute("MY_FIELD")]
public override MyField {get;set;}
}
[Serializable]
public class Class2 : MyAbstract
{
[XmlAttribute("my_field")]
public override MyField {get;set;}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.