IXmlSerialized 和不变性

发布于 2024-11-17 16:51:31 字数 423 浏览 4 评论 0原文

我正在一个不可变的类中实现 IXmlSerialized 。为了保持类不可变,我显式实现接口,以便隐藏方法,并使用封装 ReadXml(XmlReader reader) 方法的静态 ReadXml() 方法相反,返回我的类的一个新实例。但是,假设该类名为 ClassA,我被迫实现 IXmlSerialized 的方式意味着语句

((ClassA)((IXmlSerializing)(ClassAObject) ).ReadXml(reader))

实际上改变了 ClassAObject 因为,在 IXmlSerialized.ReadXml 中我分配给一个已经创建的对象。也就是说,ClassAObject 仍然可以被认为是不可变的吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

甜妞爱困 2024-11-24 16:51:32

不。

显式实现接口并不是为了“隐藏”方法 - 只是为了避免两个接口定义具有相同签名的成员时出现歧义。 “隐藏”方面也是可用的,但只是为了防止您自己的代码中出现错误 - 您必须显式转换对象,这意味着您知道自己在做什么。

添加:但是...也许您可以通过在调用 ReadXml() 后“锁定”它来非常接近不可变对象,因此进一步调用它会抛出异常一个例外。因此,对象在被读取后就变得不可变。如果您还锁定了该对象(如果该对象是由另一个构造函数而不是无参数构造函数构造的),那就太好了。根据您首先想要不变性的原因,这可能适合您的需求。

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.

软糖 2024-11-24 16:51:32

我认为您应该考虑数据传输对象(DTO),它具有公共 getters/setters 只是为了传输序列化对象数据。

I think you should consider Data Transfer Objects (DTOs) which would have public getters/setters just to transfer the serialized object data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文