C#中const和readonly有什么区别? [英] What is the difference between const and readonly in C#?
本文介绍了C#中const和readonly有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
const
和 readonly
有什么区别>在C#中?
What is the difference between const
and readonly
in C#?
什么时候可以使用另一个?
When would you use one over the other?
推荐答案
分开
- 的明显差异,必须在定义
const $时声明值c $ c> VS
只读
的值可以动态计算,但是需要在构造函数退出之前分配。在冻结之后。 - 'const是隐式
static
。您使用ClassName.ConstantName
表示法来访问它们。
- having to declare the value at the time of a definition for a
const
VSreadonly
values can be computed dynamically but need to be assigned before the constructor exits.. after that it is frozen. - 'const's are implicitly
static
. You use aClassName.ConstantName
notation to access them.
细微的差别。考虑在 AssemblyA
中定义的类。
There is a subtle difference. Consider a class defined in AssemblyA
.
public class Const_V_Readonly
{
public const int I_CONST_VALUE = 2;
public readonly int I_RO_VALUE;
public Const_V_Readonly()
{
I_RO_VALUE = 3;
}
}
组件B
引用 AssemblyA
并在代码中使用这些值。编译时,
AssemblyB
references AssemblyA
and uses these values in code. When this is compiled,
- 对于
const
值,是就像查找替换一样,值2被烘焙到AssemblyB
的IL中。这意味着,如果明天我以后将I_CONST_VALUE
更新为20。在重新编译之前,AssemblyB
仍然会有2个。 - 对于
只读
值,就像对存储位置的ref
。该值未包含在AssemblyB
的IL中。这意味着,如果内存位置已更新,AssemblyB
将获得新值,而无需重新编译。因此,如果I_RO_VALUE
更新为30,则只需要构建AssemblyA
。所有客户端都不需要重新编译。
- in the case of the
const
value, it is like a find-replace, the value 2 is 'baked into' theAssemblyB
's IL. This means that if tomorrow I'll updateI_CONST_VALUE
to 20 in the future.AssemblyB
would still have 2 till I recompile it. - in the case of the
readonly
value, it is like aref
to a memory location. The value is not baked intoAssemblyB
's IL. This means that if the memory location is updated,AssemblyB
gets the new value without recompilation. So ifI_RO_VALUE
is updated to 30, you only need to buildAssemblyA
. All clients do not need to be recompiled.
因此,如果您确信常量的值不会改变,请使用 const
。
So if you are confident that the value of the constant won't change use a const
.
public const int CM_IN_A_METER = 100;
但是如果您有一个常数可能会改变(例如,精度),或者有疑问,请使用只读
。
But if you have a constant that may change (e.g. w.r.t. precision).. or when in doubt, use a readonly
.
public readonly float PI = 3.14;
更新:Aku需要提及,因为他首先指出了这一点。另外,我还需要在我学到的地方插入。.有效的C#-Bill瓦格纳
这篇关于C#中const和readonly有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文