What is the difference between const and readonly in C#?(C# 中的 const 和 readonly 有什么区别?)
问题描述
C#中的const和readonly有什么区别?
What is the difference between const and readonly in C#? 
你什么时候会使用其中一个?
When would you use one over the other?
推荐答案
除了明显的区别
- 必须在定义 
const时声明值 VSreadonly值可以动态计算,但需要在构造函数退出之前分配.. 之后它被冻结了. const是隐含的static.您使用ClassName.ConstantName表示法来访问它们.
- having to declare the value at the time of a definition for a 
constVSreadonlyvalues can be computed dynamically but need to be assigned before the constructor exits.. after that it is frozen. const's are implicitlystatic. You use aClassName.ConstantNamenotation 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 并在代码中使用这些值.编译时:
AssemblyB references AssemblyA and uses these values in code. When this is compiled:
- 在 
const值的情况下,它就像一个查找替换.值 2 被烘焙到"AssemblyB的 IL.这意味着,如果明天我将I_CONST_VALUE更新为 20,AssemblyB在我重新编译之前仍然有 2. - 在 
readonly值的情况下,它就像一个ref到一个内存位置.该值未烘焙到AssemblyB的 IL.这意味着如果内存位置被更新,AssemblyB无需重新编译即可获得新值.所以如果I_RO_VALUE更新到30,只需要构建AssemblyA,所有客户端都不需要重新编译. 
- in the case of the 
constvalue, it is like a find-replace. The value 2 is 'baked into' theAssemblyB's IL. This means that if tomorrow I updateI_CONST_VALUEto 20,AssemblyBwould still have 2 till I recompile it. - in the case of the 
readonlyvalue, it is like arefto a memory location. The value is not baked intoAssemblyB's IL. This means that if the memory location is updated,AssemblyBgets the new value without recompilation. So ifI_RO_VALUEis updated to 30, you only need to buildAssemblyAand 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;
但如果您有一个可能会改变的常量(例如 w.r.t. 精度).. 或者有疑问时,请使用 readonly.
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 需要提及,因为他首先指出了这一点.我还需要插入我学到的地方:Effective C# - Bill Wagner
这篇关于C# 中的 const 和 readonly 有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 中的 const 和 readonly 有什么区别?
				
        
 
            
        - Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
 - 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
 - 如何用自己压缩一个 IEnumerable 2022-01-01
 - WebMatrix WebSecurity PasswordSalt 2022-01-01
 - C# 中多线程网络服务器的模式 2022-01-01
 - C#MongoDB使用Builders查找派生对象 2022-09-04
 - 输入按键事件处理程序 2022-01-01
 - MoreLinq maxBy vs LINQ max + where 2022-01-01
 - 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
 - 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
 
						
						
						
						
						
				
				
				
				