ReadOnlyCollection的Xml序列化
本文关键字:序列化 Xml ReadOnlyCollection | 更新日期: 2023-09-27 18:00:50
我有一些容器类,它们通过ReadOnlyCollection公开它们的集合。为从集合中添加和删除提供了自定义方法,这些方法还执行一些自定义逻辑。
例如:
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
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; }
}
这一切都很好,但当我使用XmlSerializer序列化Foo时,会引发异常。
有人能提供一个好的方法吗?
感谢
事实上,这是行不通的。所以不要那样做。此外,除了非常痛苦的IXmlSerializable
之外,没有任何钩子可以检测xml序列化。
所以要么:
- 不要在此处使用只读集合
- 实施
IXmlSerializable
(棘手( - 有一个双重API(一个只读,一个非;序列化"非"-由于
XmlSerializer
只处理publicx成员,所以很棘手( - 使用单独的DTO进行序列化
不能反序列化ReadOnlyCollection
,因为它没有Add
方法。要修复此问题,请使用第二个属性进行序列化:
[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序列化仅序列化具有getter和setter的属性。您可以使用SoapFormatter、BinaryFormatter或DataContractSerializer。