【问题标题】:Serialize to XML a class containing a struct将包含结构的类序列化为 XML
【发布时间】:2014-10-04 07:41:52
【问题描述】:

这是我要序列化的类

[Serializable]
public class PendingAccountInfo 
{
        public AccountId AccountId { get; set; }
        public string EmailAddress { get; set; }
}

[Serializable]
public struct AccountId : IEquatable<AccountId> 
{
    private readonly int _id;

    public AccountId(int id) {
        _id = id;
    }

    public int Id {
        get { return _id; }
    }
    ...
}

这就是我进行序列化的方式

XmlSerializer xmlserializer = new XmlSerializer(typeof(List<T>));
StringWriter stringWriter = new StringWriter();

XmlWriterSettings settings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true };

XmlWriter writer = XmlWriter.Create(stringWriter, settings);

xmlserializer.Serialize(writer, value);

string result = stringWriter.ToString();

这就是我得到的

<PendingAccountInfo>
  <AccountId />
  <EmailAddress>test@test.com</EmailAddress>
</PendingAccountInfo>

根据我的阅读,这应该可以,但我一定是遗漏了一些东西

【问题讨论】:

  • 为属性Id 写一个公共的getter/setter。可能还需要一个空的构造函数...

标签: c# xml serialization struct


【解决方案1】:

这里的问题来自您的 readonly 属性。正如other thread 中所述,XmlSerializer 仅序列化具有 get/set 可访问性的属性。

您可以做的是让您的属性可设置或更改您的序列化程序。

【讨论】:

  • 谢谢,我已经尝试使属性可设置,但我忘记了该属性是只读的...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-25
  • 1970-01-01
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多