C# 将包含结构的类序列化为XML

C# 将包含结构的类序列化为XML,c#,xml,serialization,struct,C#,Xml,Serialization,Struct,这就是我试图序列化的类 [Serializable] public class PendingAccountInfo { public AccountId AccountId { get; set; } public string EmailAddress { get; set; } } [Serializable] public struct AccountId : IEquatable<AccountId> { private rea

这就是我试图序列化的类

[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; }
    }
    ...
}
[可序列化]
公共类PendingAccountInfo
{
public AccountId AccountId{get;set;}
公共字符串电子邮件地址{get;set;}
}
[可序列化]
公共结构帐户ID:IEquatable
{
私有只读int_id;
公共帐户id(内部id){
_id=id;
}
公共整数Id{
获取{return\u 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();
XmlSerializer XmlSerializer=新的XmlSerializer(typeof(List));
StringWriter StringWriter=新StringWriter();
XmlWriterSettings=new XmlWriterSettings{OmitXmlDeclaration=true,Indent=true};
XmlWriter=XmlWriter.Create(stringWriter,设置);
serializer.Serialize(writer,value);
字符串结果=stringWriter.ToString();
这就是我得到的

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

test@test.com

从我读到的内容来看,这应该是可行的,但我肯定遗漏了一些东西。这里的问题来自您的只读属性。如本文所述,XmlSerializer仅序列化具有get/set可访问性的属性


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

为属性
Id
编写公共getter/setter。可能还需要一个空的构造函数…谢谢,我已经尝试将属性设置为可设置的,但是我忘记了该属性是只读的。。。