不要声明只读的可变引用类型-为什么不呢? [英] Do not declare read only mutable reference types - why not?

查看:119
本文介绍了不要声明只读的可变引用类型-为什么不呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读这问题和其他一些答案,虽然我得到了更改引用和更改当前实例的状态之间的区别,但我不确定为什么这意味着我不应该将其标记为只读.这是因为将某些内容标记为只读会告诉编译器有关实例的一些特殊信息,因此当它实际上可能不是实例时,便可以将其视为线程安全的吗?

I have been reading this question and a few other answers and whilst I get the difference between changing the reference and changing the state of the current instance I'm not certain why this means that I shouldn't mark it readonly. Is this because marking something as readonly tells the compiler something special about the instance and so it is able to then treat it as thread safe when it actually might not be?

大概在某些情况下,我不希望更改实例,但是不介意实例的状态是否已更改(可能是单个,/me为发生火焰做准备)会导致什么后果?如果需要,将实例标记为只读?

Presumably there are situations where I don't want the instance to be able to be changed, but don't mind if the state of the instance is changed (singleton maybe. /me prepares for flames) What are the consequences for marking the instance readonly if I want this?

推荐答案

没有(基于运行时/环境的)后果.编译器不会发狂,您的运行时不会爆炸,并且一切都会正常.

There are no (runtime/environment-based) consequences. The compiler won't freak out, your runtime won't explode, and everything will generally be fine.

只有FxCop(某些人使用的静态分析工具)对此有警告.警告的原因在您链接到的线程中进行了解释(显然,可能不清楚该对象实际上不是只读"对象,而只是无法重新分配"该变量).

It's only FxCop (a static analysis tool that some people use) that has a warning about this. The reasons for the warning are explained in the thread you've linked to (semantically, it may not be clear that the object isn't actually "readonly", only that the variable can't be "reassigned").

我个人不同意该规则,因此我将其禁用(如果您正在运行FxCop并且它与您有关).

Personally, I disagree with the rule, so I'd just disable it (if you're running FxCop and it is concerning you).

这篇关于不要声明只读的可变引用类型-为什么不呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆