简体   繁体   English

IXmlSerializable 和 Immutability

[英]IXmlSerializable and Immutability

I am implementing IXmlSerializable in an immutable class.我在不可变的 class 中实现IXmlSerializable To keep the class immutable I am implementing the interface explicitly, so as to hide the methods, and using a static ReadXml() method which encapsulates the ReadXml(XmlReader reader) method and, instead, returns a new instance of my class.为了保持 class 不可变,我正在显式实现接口,以便隐藏方法,并使用封装了ReadXml(XmlReader reader)方法的 static ReadXml()方法,而是返回我的 ZCBB14F2ED4F8EBC402 的新实例。 However, and supposing the class is called ClassA , the way I am forced to implement IXmlSerializable implies that the statement但是,假设 class 被称为ClassA ,我被迫实现IXmlSerializable的方式意味着该语句

((ClassA)((IXmlSerializable)(ClassAObject)).ReadXml(reader))

actually mutates the ClassAObject since, inside IXmlSerializable.ReadXml I am assigning to parameters of an already created object.实际上改变了ClassAObject ,因为在IXmlSerializable.ReadXml中我分配给已经创建的 object 的参数。 That being, can ClassAObject still be considered immutable?也就是说, ClassAObject仍然可以被认为是不可变的吗?

No.不。

Explicitly implementing interfaces is not meant for "hiding" methods - just for avoiding ambiguities when two interfaces define members with the same signature.显式实现接口并不意味着“隐藏”方法 - 只是为了避免在两个接口定义具有相同签名的成员时产生歧义。 The "hiding" aspect is also usable, but only to prevent mistakes in your own code - you have to explicitly cast the object, which means that you know what you are doing. “隐藏”方面也可以使用,但只是为了防止您自己的代码出错——您必须显式转换 object,这意味着您知道自己在做什么。

Added: However... maybe you can get pretty close to an immutable object by "locking" it after ReadXml() has been called, so further calls to it would throw an exception.补充:但是...也许您可以通过在调用ReadXml()之后“锁定”它来非常接近不可变的 object,因此进一步调用它会引发异常。 Hence the object becomes immutable after it has been read.因此 object 在被读取后变得不可变。 It would be great if you also locked the object if it was constructed by another constructor than the parameterless one.如果 object 是由另一个构造函数而不是无参数构造函数构造的,那将是非常棒的。 Depending on why you want the immutability in the first place, this could suit your needs.根据您首先想要不变性的原因,这可能适合您的需求。

I think you should consider Data Transfer Objects (DTOs) which would have public getters/setters just to transfer the serialized object data.我认为您应该考虑具有公共 getter/setter 的数据传输对象 (DTO),以传输序列化的 object 数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM