常量和只读之间的区别是什么? [英] What is the difference between const and readonly?

查看:195
本文介绍了常量和只读之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间的区别是什么 常量 只读 和你比其他使用一个?

What is the difference between const and readonly and do you use one over the other?

推荐答案

除了的明显差异

  • 具有一个常量的定义时声明价值 VS 只读值可以动态计算但需要构造函数退出之前被分配..之后,它被冻结。
  • 在常量的隐含静态。您可以使用 ClassName.ConstantName 符号来访问它们。
  • having to declare the value at the time of a definition for a const VS readonly 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 a ClassName.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;
  }
}

AssemblyB 引用 AssemblyA 并使用code这些值。当这个被编译,

AssemblyB references AssemblyA and uses these values in code. When this is compiled,

  • 常量值的情况下,它就像一个查找替换,值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' the AssemblyB's IL. This means that if tomorrow I'll update I_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 a ref to a memory location. The value is not baked into AssemblyB's IL. This means that if the memory location is updated, AssemblyB gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA. All clients do not need to be recompiled.

所以,如果你有信心,常量的值不会改变使用常量

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;

但是,如果你有一个恒定的,可能会改变(egwrt precision)..或有疑问时,可使用只读

public readonly float PI = 3.14;

更新:阿库需要得到一提的表兄弟姐妹,他指出了这一点首位。此外,我要插在那里我学到这个.. 有效的C#比尔 - 瓦格纳

这篇关于常量和只读之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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