可序列化类:集合属性的自定义序列化器

发布于 2025-01-23 01:41:35 字数 310 浏览 2 评论 0原文

我有一个XML-Serializable .NET类,该类具有类型列表的属性< gt;。出于向后兼容的原因,我需要将此属性序列化/对单个逗号分隔的字符串进行序列化。像:

<MyProperty>ID1;ID2;ID3</MyProperty>

是否可以仅针对可序列化类的特定属性指定自定义序列化器?另外,可以为其实现Iserializable/ixmlSerializable,但是在这种情况下,我希望仅将代码保留到最小处理中,仅处理该属性并默认保留其余部分。

有什么想法吗?

谢谢!

I have an xml-serializable .net class which has a property of type List<string>. For backward-compatibility reasons I need to serialize/deserialize this property as a single comma-separated string. Like:

<MyProperty>ID1;ID2;ID3</MyProperty>

Is it possible to specify a custom serializer for only a particular property of a serializable class? Alternatively it is ok to implement ISerializable/IXmlSerializable for it, but in this case I would prefer to keep code to the minimum processing only that property and keeping the rest by default.

Any ideas?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

陌上青苔 2025-01-30 01:41:35

XMLSerializer不支持此属性。为什么会击败XML的目的。 XML有儿童道具来解决这个问题。

您可以将道具作为修复程序计算,但是如果列表变大,这并不干净和慢。

[XmlAttribute(AttributeName = "attributeName")]
public string MyPropString{ get; set; }

public IList<string> MyProperty{
    get {
        return MyPropString.Split(';').Select(x => x.Trim()).ToList();
    }
    set {
       MyPropString = String.Join(";", value);
    }
}

此代码可能是错误的,因为我没有测试过,但是我希望您明白这个想法。

XmlSerializer does not support this out of the box for attributes. And why would it, it kinda beats the purpose of XML. Xml has child props to handle this issue.

You could calculate your props as a fix, but this isn't clean and pretty slow if the list gets big.

[XmlAttribute(AttributeName = "attributeName")]
public string MyPropString{ get; set; }

public IList<string> MyProperty{
    get {
        return MyPropString.Split(';').Select(x => x.Trim()).ToList();
    }
    set {
       MyPropString = String.Join(";", value);
    }
}

This code could be wrong because i haven't tested it, but i hope you get the idea.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文