Xml Serialization of ReadOnlyCollections
I have some container classes that expose their collections through a ReadOnlyCollection. Custom Methods are provided to Add and Remove from the collection which also perform some custom logic.
For example:
public class Foo
{
List<Bar> _barList = new List<Bar>();
public ReadOnlyCollection<Bar> BarList
{
get { return _barList.AsReadOnly(); }
}
public void AddBar(Bar bar)
{
if (bar.Value > 10)
_barList.Add(bar);
else
开发者_JAVA技巧 MessageBox.Show("Cannot add to Foo. The value of Bar is too high");
}
public void RemoveBar(Bar bar)
{
_barList.Remove(bar);
// Foo.DoSomeOtherStuff();
}
}
public class Bar
{
public string Name { get; set; }
public int Value { get; set; }
}
This is all well and good but when i come to serialise Foo with the Xml Serializer an exception is thrown.
Can anyone offer a good way of going about this?
Thanks
Indeed, that won't work. So don't do that. Additionally, there are no hooks to detect xml serialization except the oh-so-painful IXmlSerializable
.
So either:
- don't use a read-only collection here
- implement
IXmlSerializable
(tricky) - have a dual API (one read-only, one not; serialize the "not" - tricky as
XmlSerializer
only handles publicx members) - use a separate DTO for serialization
You can't deserialize ReadOnlyCollection
because it does not has Add
method.
To fix that use a second property for serialization:
[XmlIgnore()]
public ReadOnlyCollection<Bar> BarList
{
get { return _barList.AsReadOnly(); }
}
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
//[Obsolete("This is only for serialization process", true)]
[XmlArray("BarList")]
[XmlArrayItem("Bar")]
public List<Bar> XmlBarList
{
get { return _barList; }
set { _barList = value; }
}
XML Serialization only serializes properties that have a getter and a setter. You can use the SoapFormatter, BinaryFormatter or DataContractSerializer.
精彩评论