简体   繁体   中英

IXmlSerializable and Immutability

I am implementing IXmlSerializable in an immutable class. 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. However, and supposing the class is called ClassA , the way I am forced to implement IXmlSerializable implies that the statement

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

actually mutates the ClassAObject since, inside IXmlSerializable.ReadXml I am assigning to parameters of an already created object. That being, can ClassAObject still be considered immutable?

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.

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. Hence the object becomes immutable after it has been read. It would be great if you also locked the object if it was constructed by another constructor than the parameterless one. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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