开发者

.net XmlSerializer on overridden properties

开发者 https://www.devze.com 2023-02-09 02:33 出处:网络
I have a base class with an abstract property: public abstract int ID {get;set;} now, I have a subclass, which is XmlSerialized. So, it has:

I have a base class with an abstract property:

public abstract int ID {get;set;}

now, I have a subclass, which is XmlSerialized. So, it has:

[XmlElement("something")]
public override int ID {
get { //... }
set { //... }
}

I cannot move the XmlElement attribute to baseclass, since every subclass will have a different xml elementname.

Now, when I deserialize this class I get the following error:

Member 'Subclass.ID' hides inherited member 'BaseClass.ID', but has开发者_C百科 different custom attributes.

What can I do?


Serialization and deserialization of derived types works when the overridden properties have [XmlElement] and [XmlAttribute] attributes, by adding an [XmlIgnore] attribute.

The base class can be made abstract so that it can never be instantiated and therefore serialized or deserialized.

[Serializable]
public abstract class Base
{
    [XmlIgnore]
    public abstract Int32 ID { get; set; }
}


Make the base class property protected and non-abstract, then give each derived class an appropriately named property implemented in terms of the base class property:

// Base class
protected int InternalID {get; set;}

// Derived class
[XmlElement]
public int SomethingID
{
  get {return InternalID;}
  set {InternalID = value;}
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号