序列化时的伪只读属性
多么糟糕的是:
public class Test
{
private string pKey = null;
public string Key {
get { return pKey; }
set { if (pKey==null) pKey=value;}
}
}
这将允许我将 XMLSerializer
与类一起使用,并确保 Key
在初始设置后无法更改。
How bad is something like:
public class Test
{
private string pKey = null;
public string Key {
get { return pKey; }
set { if (pKey==null) pKey=value;}
}
}
This would allow me to use XMLSerializer
with the class and make sure that Key
can't be changed after being initially set.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我承认我最初的想法很糟糕。
我现在知道无法使用标准 XML 序列化程序来实现此目的。 “ssg”建议不会被序列化,因为它没有公共设置器。
这里唯一的选择是实现
IXmlSerialized
,或使用其他序列化方法,例如DataContractSerializer
。前者的问题是该类的每个派生类还必须实现 IXmlSerializes;后者的问题是您无法使用属性或对生成的 XML 有太多控制。I agree that my initial idea was bad.
I now know that there is no way to make this using the standard XML Serializer. 'ssg' suggestion won't be serialized because it doesn't have a public setter.
The only choices here are implementing the
IXmlSerializable
, or using another serialization method, likeDataContractSerializer
. The problem with the former is that every derivate of the class would also have to implementIXmlSerializable
; the problem with the latter is that you can't use attributes or have much control over the generated XML.不好,请考虑一下:
我已经设法绕过了您的保护(显然您可以向 set 方法添加
null
检查来解决此问题)。如果反序列化对象有一个
null
键,则可能会出现同样的问题,该键仍然可以在第一次访问时设置...似乎如果您需要这种保护,您可能应该看看另一种获取方式。XMLSerializer
对您使用的类施加了限制,并且通过尝试解决这些限制,您可能会造成混乱。如果您是一家单人商店,并且您是唯一查看代码的人,那么这可能不是什么问题(至少在您离开代码几个月之前),但是在多开发人员中环境中你的班级的行为很可能会引起混乱。例如,您通过不抛出异常来隐藏不起作用的赋值,因此赋值操作将编译并运行,但不会更新对象,也不会抛出异常来指示失败(这可能会导致一些难以追踪的问题)错误)。Bad, consider:
I've managed to circumvent your protection (obviously you could add a
null
check to the set method to fix this issue).The same problem could occur if the deserialized object had a
null
key, the key could still be set the first time it was accessed... It seems like if you need this sort of protection, you should probably look at another way of getting it.The
XMLSerializer
places restrictions on the classes you use with it and by trying to work around those restrictions, you’re likely to cause confusion. If you are a one-man shop and you are the only person that looks at the code, this may be less of an issue (at least until you step away from the code for a coupld of months), however in a multi-developer environment the behaviour of your class is likely to cause confusion. For example, you’re hiding the assignment not working by not throwing an exception, so assignment operations would compile and run, but, not update the object and not throw an exception to indicate the failure (which could lead to some hard to track down bugs).