Overriding a property with an attribute

后端 未结 2 1550
暗喜
暗喜 2020-12-09 19:59

I\'m trying to find a way to change the serialization behavior of a property.

Lets say I have a situation like this:

[Serializable]
public class Reco         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-09 20:35

    The best I can think of...

    [Serializable]
    public class Record
    {
       public DateTime LastUpdated {get; set; }
       public virtual bool ShouldSerializeLastUpdated() {return true;}
       // other useful properties ...
    }
    
    public class EmployeeRecord : Record
    {
       public string EmployeeName {get; set; }
       public override bool ShouldSerializeLastUpdated() {return false;}
       // other useful properties ...
    }
    

    Basically, there are a few patterns that XmlSerializer respects; public bool ShouldSerialize*(), and public bool *Specified {get;set;} (note you should mark *Specified with [XmlIgnore] too...).

    Not very elegant, I'll grant; but XmlSerializer only looks at public members, so you can't even hide them (short of [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]).

提交回复
热议问题