为了混淆应用程序代码但仍然能够使用序列化来保存应用程序数据,我想将所有序列化成员的名称映射到自定义序列化名称。 我知道我可以通过实现 ISerizableInterface 来实现此目的,但在 MSDN 中,他们建议使用 OnDeserializedAttribute、OnSerializingAttribute、OnSerializedAttribute 和 OnDeserializingAttribute 进行序列化。 所以我想使用 OnSerializingAttribute 来重命名我的成员。 问题是我找不到一种方法来显式确定序列化成员的名称。
是否可以使用 OnSerializingAttribute 显式定义序列化名称?
in order to obfuscate application code but still be able to use serialization to save application data, I want to map the names of all serialized members to custom serialization names. I know that I can achieve this by implementing the ISerizableInterface, but in the MSDN they suggest the use of OnDeserializedAttribute, OnSerializingAttribute, OnSerializedAttribute, and OnDeserializingAttribute for serialization. So I would like to use the OnSerializingAttribute to rename my members. The problem is that I can't find a way to explicitly determine the names under which a member is serialized.
Is it possible to explicitly define the names for serialization using the OnSerializingAttribute?
发布评论
评论(3)
我认为自定义序列化和 ISerialized 接口将是您的情况下最有效的方法。 请查看此处的示例。 另外这里 针对您提到的 ISerialized 和序列化属性的一个很好的讨论线程。
我想说,如果您想完全控制格式,您应该使用自定义序列化程序,如果您想响应(反)序列化流程,则属性是最佳选择。
I think custom serialization and ISerializable interface will be the most efficient way in your case. Check out the sample here. Also here's a good discussion thread towards both ISerializable and serialization attributes you've mentioned.
I would say that if you want to have a full control over the format you should use custom serializer and if you want responding the (de)serialization flow the attributes is the best option.
(编辑:我决定将其写为 博客条目,因为我已经多次看到它很有用)
我在使用之前就有用户protobuf-net 为此; 这使用谷歌的密集二进制“协议缓冲区”线路格式,其中不包括线路上的任何名称 - 只是数字。 这意味着:
这通过为成员(属性或字段)分配整数标记来工作 - 例如:
序列化中仅使用“4”,但(重要的是)您不需要维护大量序列化代码。 如果您需要使用远程处理,也可以非常轻松地连接到
ISerialized
,如果需要,还可以使用 WCF 钩子。披露:我是作者,所以我有偏见 - 但该工具是免费的,所以你不会因为查看而失去任何东西;-p
(edit: I decided to write this up as a blog entry, as I've seen it be useful a number of times)
I've had users before use protobuf-net for this; this uses Google's dense binary "protocol buffers" wire format, which doesn't include any names on the wire - just numbers. This means that:
This works by assigning an integer tag to members (properties or fields) - for example:
Only the "4" is used in the serialization, but (importantly) you don't need to maintain lots of serialization code. Can also be hooked into
ISerializable
very easily if you need to use remoting, and also has a WCF hook if you want.Disclosure: I'm the author, so I'm biased - but the tool is free, so you don't lose anything by having a look ;-p
如果您使用 .NET4 或 .NET4.5,您可以定义自己的 DataContractResolver 来重命名属性,但在
[DataMember(...)]
中使用压缩命名会更简单属性If you're using .NET4 or .NET4.5 you can define your own DataContractResolver to rename the attributes, but it would be simpler to just use compacted named in the
[DataMember(...)]
attribute