如何将默认值添加到 XmlSerialized 列表而不重复?
我已经遇到过这个问题几次并且有解决方案,但没有一个是我喜欢的。考虑有这样一个类:
public class MyData
{
public List<string> Values = new List<string>();
}
假设我总是希望值至少有一个值,并且该值应该是“默认”。构造函数可能是:
public MyData()
{
Values.Add("Default");
}
确保新实例始终至少具有“默认”条目。问题是,如果我 XmlSerialize 一个新实例,它将使用值中的“默认”值进行序列化。这本身是可以的,但是当我反序列化它时,默认值会添加到我的构造函数中,然后再次通过反序列化,导致“默认”值重复。
就像我上面提到的,我做了一些特殊的事情,比如创建 Load 和 Save 方法,在内部进行序列化并检查重复项,但如果有人在不通过这些方法的情况下序列化/反序列化实例,这可能会很危险。以前有人遇到过这个问题吗?有标准的方法来解决吗?
I've run into this problem a few times and have solutions for it, but none that I like. Consider having a class like:
public class MyData
{
public List<string> Values = new List<string>();
}
Let's say that I always want Values to have at least one value,and this value should be "Default". The constructor might be:
public MyData()
{
Values.Add("Default");
}
That guarantees that new instances will always have at least the "Default" entry. The problem is if I XmlSerialize a new instance, it will serialize with the "Default" value in Values. That by itself is okay, but when when I deserialize it, the Default value gets added in my constructor, then once again through the deserialization, causing a duplicate value for "Default".
Like I mentioned above, I have done special things like making Load and Save methods that do the serialization internally and check for duplicates but that could be dangerous if someone serializes/deserializes the instance without passing through those methods. Has anyone ever encountered this problem before? Are there standard ways to solve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论