自动属性的实现是否在规范中?
我可以相信名为 Foo 的属性的基础字段称为“k__BackingField”吗?
Can I rely on the fact that the underlying field to a property named Foo is called "k__BackingField" ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,简而言之。
正是由于这个原因,自动属性在与像 BinaryFormatter 这样的基于字段的序列化器一起使用时会很痛苦(我确信我之前可能已经提到过;-p)。
有关一些想法,请参阅:混淆、序列化和自动实现的属性这个(和解决方案)。
No, in short.
And for this very reason, auto-properties are pain when used with field-based serializers like
BinaryFormatter
(I'm sure I might have mentioned that here before ;-p).See: Obfuscation, serialization and automatically implemented properties for some thoughts on this (and a solution).
该规范没有指定支持字段的名称(有充分的理由 - 您不应该依赖它)。
例如,您应该调查一下 Mono 编译器是否会做同样的事情。
健全性检查该字段是否应用了 CompilerGeneratedAttribute 是一个好主意。
请注意,显式接口实现(当前)将如下所示:
因此,尝试以这种方式序列化类的特定方面的代码可能会被误导。
如果你想真正了解你的代码,你可以使用像 mono 的 Cecil 这样的库来检查属性的 get 函数并确定所使用的字段。
That the spec does not specify the backing field's name (with good reason - you shouldn't take a dependency on it).
You should investigate to see whether the Mono compiler does the same thing for example.
Sanity checking that the field had the
CompilerGeneratedAttribute
applied to it would be a good idea.Note that explicit interface implementations would come out (currently) as:
So code which is trying to serialize a specific aspect of a class in this fashion could be mislead.
If you wanted to be really belt and braces about your code you could use a library like mono's Cecil to inspect the get function of the property and determine the field used.
当然不是。 这将是一个私有实现细节。
你到底为什么想知道?
Of course not. That would be a private implementation detail.
And why on Earth would you want to know?
我不这么认为。 如果您需要支持字段,请使用“常规”属性。
I don't think so. If you need the backing field, use a 'regular' property.