XmlSerializer:如何允许属性反序列化,然后阻止它序列化?
也就是说,我希望我的数据以一种方式进行 - 输入到一个类中,但随后防止它在序列化操作期间保存。最好的方法是什么?
That is, I'd like my data to go one way - feed into a class, but then prevent it from saving out during a serialize operation. What's the best way to go about that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的方法是序列化一个正确执行
Set
但始终在Get
上返回固定假值的属性。例如,如果该属性名为Password
,您将创建一个适合上述设计的SerializedPassword
属性,而不序列化原始属性。编辑
这是 Ani 的示例,已格式化,但做了一处更改:
The simplest way is to serialize a property that does
Set
correctly but always returns a fixed, fake value onGet
. For example, if the property were calledPassword
, you'd create aSerializablePassword
property that fits the above design, while not serializing the original.edit
Here's Ani's sample, formatted, with one change:
如果您希望完全控制序列化过程,可以实现接口 可序列化。
还要实现特殊的构造函数。
编辑:
我的意思是IXmlSerialized。谢谢约翰。
If you like the full control over the serialization process you can implement the interface ISerializable.
Also implement the special constructor.
EDIT:
I meant IXmlSerializable. Thanks John.
好吧,我尝试了
return null;
建议,但它不起作用;它无法反序列化。但是,这里有一个解决方法:虽然性能可能不是很好,但它会检查 StackTrace 以查看谁调用了 get - 如果是 Serializer/Writer,则不会返回任何内容。
Ok, I tried the
return null;
suggestion, but it doesn't work; it fails to deserialize. However, here's a workaround:While probably not very performant, this examines the StackTrace to see who called the
get
- and if it's the Serializer/Writer, it returns nothing.