Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a class I've marked as Serializable, with a Uri property. How can I get the Uri to serialize/Deserialize without making the property of type string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
320 views
Welcome To Ask or Share your Answers For Others

1 Answer

With xml serializer, you are limited - it isn't as versatile as (say) some of the binaryformatter/ISerializable options. One frequent trick is to have a second property for serialization:

[XmlIgnore]
public Uri Uri {get;set;}

[XmlAttribute("uri")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public string UriString {
    get {return Uri == null ? null : Uri.ToString();}
    set {Uri = value == null ? null : new Uri(value);}
}

The two browsable attributes hide it from view (but it needs to be on the public API for XmlSerializer to use it). The XmlIgnore tells it not to try the Uri; and the [XmlAttribute(...)] (or [XmlElement(...)]) tells it to rename UriString when (de)serializing it.

(note that EditorBrowsable only applies to code outside the assembly declaring the type)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...