我想将不可变对象序列化和反序列化为XML。如何使用XmlSerializer实现该目标?
我已经从中实现了ISerializable接口和方法GetObjectData,但是XmlSerializer忽略了它。显然,当通过Newtonsoft.Json转换为JSON时,一切都很好。我知道我可以通过将代码重构为DataContractSerializer来实现这一目标,但是我想将现有的XmlSerializer保留在解决方案中。我的不变对象的结构定义如下。
[Serializable]
public class CustomerNumberDefinition : ISerializable
{
private CustomerNumberDefinition()
{
}
private CustomerNumberDefinition(SerializationInfo info, StreamingContext text)
: this()
{
this.KlpUserNumber = info.GetString(nameof(this.KlpUserNumber));
this.RawCustomerNumber = info.GetString(nameof(this.RawCustomerNumber));
}
private CustomerNumberDefinition(string customerNumber, string klpUserNumber)
{
this.RawCustomerNumber = customerNumber;
this.KlpUserNumber = klpUserNumber;
}
public string KlpUserNumber { get; }
public string RawCustomerNumber { get; }
public static CustomerNumberDefinition Create(string customerNumber, string klpUserNumber)
{
return new CustomerNumberDefinition(customerNumber, klpUserNumber);
}
[SecurityPermission(SecurityAction.Assert, SerializationFormatter = true)]
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(this.KlpUserNumber), this.KlpUserNumber);
info.AddValue(nameof(this.RawCustomerNumber), this.RawCustomerNumber);
}
}
我希望当尝试通过XmlSerializer序列化CustomerNumberDefinition类的实例时,将调用GetObjectData(),但不会发生。