如何将默认值添加到 XmlSerialized 列表而不重复?

发布于 2025-01-08 13:50:14 字数 532 浏览 5 评论 0原文

我已经遇到过这个问题几次并且有解决方案,但没有一个是我喜欢的。考虑有这样一个类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文