不变性和XML序列化 [英] Immutability and XML Serialization
问题描述
我有几个班,一旦他们设定初始值是不可改变的。埃里克利珀称这直写一旦不变性。
I have several classes that are immutable once their initial values are set. Eric Lippert calls this write-once immutability.
实施一次性写入不变性在C#中通常是指通过构造函数设置的初始值。这些值初始化只读域。
Implementing write-once immutability in C# usually means setting the initial values via the constructor. These values initialize readonly fields.
但是,如果您需要序列化类像这样的XML,即使用的XmlSerializer或DataContractSerializer的,你必须有一个无参数的构造函数。
But if you need to serialize a class like this to XML, using either the XmlSerializer or the DataContractSerializer, you must have a parameterless constructor.
有没有人有关于如何解决此问题的建议吗?是与序列化更好地工作,还有其他形式的不变性
Does anyone have suggestions for how to work around this problem? Are there other forms of immutability that work better with serialization?
编辑:由于@Todd指出,DataContractSerializer的不需要参数的构造函数。根据MSDN上中的的DataContractSerializer文件,DataContractSerializer的不叫。目标对象的构造函数
As @Todd pointed out, the DataContractSerializer does not require a parameterless constructor. According to the DataContractSerializer documentation on MSDN, DataContractSerializer "does not call the constructor of the target object."
推荐答案
假设这是你的不可变的对象:
Assuming this is your "immutable" object :
public class Immutable
{
public Immutable(string foo, int bar)
{
this.Foo = foo;
this.Bar = bar;
}
public string Foo { get; private set; }
public int Bar { get; private set; }
}
您可以创建一个虚拟类来表示序列化/反序列化过程中不可变对象
You can create a dummy class to represent that immutable object during serialization/deserialization :
public class DummyImmutable
{
public DummyImmutable(Immutable i)
{
this.Foo = i.Foo;
this.Bar = i.Bar;
}
public string Foo { get; set; }
public int Bar { get; set; }
public Immutable GetImmutable()
{
return new Immutable(this.Foo, this.Bar);
}
}
当你有不可变类型的属性,不要 ŧ序列化,而是序列化DummyImmutable:
When you have a property of type Immutable, don't serialize it, and instead serialize a DummyImmutable :
[XmlIgnore]
public Immutable SomeProperty { get; set; }
[XmlElement("SomeProperty")]
public DummyImmutable SomePropertyXml
{
get { return new DummyImmutable(this.SomeProperty); }
set { this.SomeProperty = value != null ? value.GetImmutable() : null; }
}
OK,这是有点长了东西,看起来这么简单.. 。但它应该工作;)
OK, this is a bit long for something that looks so simple... but it should work ;)
这篇关于不变性和XML序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!