强制仅从序列化中调用构造函数
在我们的代码库中,任何需要保存的类都是 IXmlSerialized,这意味着它们都具有公共无参数构造函数。
这样做的问题是,我必须在每个成员上方添加注释“仅用于序列化目的”,因为这些实例上的某些成员是私有的且是必需的,因此在调用所有“可用”构造函数时是必需的。
真正好的方法是“这个构造函数只能由序列化代码/程序集调用,否则我会爆炸”。有人知道是否有一个好的方法来做到这一点?我能想到的唯一方法是检查调用堆栈,为什么听起来太贵了......
In our codebase any classes that need to be saved are IXmlSerializable, this means that they all have public parameterless constructors.
The problem with this, is I have to stick a remark above each one "Only for serialization purposes" because certain members on these instances are private and required, and are therefore required when calling all the 'usable' constructors.
What would be really nice is a way of saying "This constructor must only be called by serialization code/assemblies, otherwise I'm going to explode". Anyone know if there's a nice way to do this? They only way I can think of this is checking the call stack why sounds too expensive...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
怎么样:
注意:这不会保护您免受反射或带有
where T : new()
约束的泛型的影响,但它避免了更可能的新的 Foo() 场景。
How about:
Note: this won't protect you from reflection, or from generics with the
where T : new()
constraint, but it avoids the more likelynew Foo()
scenario.我为您提供了另一个解决方案:将“私有”构造函数移出类,并使用 序列化代理 - 这样你的神奇构造函数将永远不会在序列化之外使用,因为它现在是序列化过程本身的一部分。
I have another solution for you: move your 'private' constructor out of your class, and use a serialization surrogate - that way your magic constructor will never be used outside of serialization as it's now part of the serialization process per se.