C# - FieldInfo 和 PropertyInfo 是不可变的还是可变的?
基本上,我有以下内容:
protected static readonly FieldInfo SpecialField = FindSpecialField();
FxCop 向我抱怨,如果字段是可变的,我不应该将其设置为只读,因为成员可以更改。 FieldInfo 和 PropertyInfo 是不可变的还是可变的。基本上,我可以抑制此消息吗?
Basically, I have the following:
protected static readonly FieldInfo SpecialField = FindSpecialField();
FxCop is complaining to me though that I should not make a field readonly if it is mutable because the members can be changed. Are FieldInfo and PropertyInfo immutable or mutable. Basically, can I suppress this message?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
FieldInfo 本身看起来是不可变的,但它的变体可能是也可能不是。例如,可以修改 FieldBuilder。 PropertyInfo 也是如此。
因此,如果您知道它始终是从反射获得的 FieldInfo,那么您很可能会安全。
FieldInfo itself looks immutable, but derviations of it may or may not be. For example, the FieldBuilder can be modified. Same holds for PropertyInfo.
So, if you know it's always a FieldInfo obtained from reflection, then chances are you will be safe.
我想说它们是不可变的。没有成员可以更改
FieldInfo
和PropertyInfo
实例的状态。SetValue()
方法更改 Field/Property 所属实例(或类的静态成员)的值,但不会更改 FieldInfo/PropertyInfo 本身。I would say they are Immutable. There are no members to change the state of instances of
FieldInfo
andPropertyInfo
. TheSetValue()
method changes the value of the instance (or the class's static members) to which the Field/Property belongs to but not the FieldInfo/PropertyInfo itself.虽然我从未见过我所知道的可变类,但这些都是基类,谁知道派生类会是什么样子。
While I've never seen one that I've known to be mutable, those are base classes, and who knows what the derived classes could be like.