简体   繁体   English

const与只读

[英]const vs. readonly

Today I found an article where a const field is called compile-time constant while a readonly field is called runtime constant . 今天,我找到了一篇文章,其中const字段称为编译时常量,readonly字段称为运行时常量 The two phrases come from 《Effective C#》. 这两个词来自《有效的C#》。 I searched in MSDN and the language spec, find nothing about runtime constant . 我在MSDN和语言规范中进行了搜索,但未找到有关运行时常量的任何信息。

No offensive but I don't think runtime constant is a proper phrase. 没有冒犯性,但是我不认为运行时常量是正确的说法。

private readonly string foo = "bar";

creates a variable named "foo", whose value is "bar", and the value is readonly, here it is a variable, no business on constant . 创建一个名为“ foo”的变量,其值为“ bar”,并且该值是只读的,这里它是一个变量, constant上没有任何作用。 A readonly variable is still a variable, it can't be a constant. 只读变量仍然是变量,不能为常量。 Variable and constant are mutually exclusive. 变量和常量是互斥的。

Maybe this question goes overboard, still I want to listen to others' opinions. 也许这个问题太过分了,但我还是想听听别人的意见。 What do you think? 你怎么看?

I believe that author means the following: 我相信作者的意思是:

Consider example: 考虑示例:

public class A {

     public const int a = Compute();         

     private static int Compute(){

          /*some computation and return*/ 
          return some_computed_value;
     }
}

this, will not compile, as you have to have constant value to assign to a . 这一点, 将不能编译,因为你必须有恒定值分配给a So this is a meaning of compile-time constant . 因此, 这是 编译时常 的含义。

Instead if you change this to 相反,如果您将其更改为

public class A {

     public readonly int a = Compute();          

     private static int Compute(){
          /*some computation and return*/ 
          return some_computed_value;
     }
}

this will compile. 编译。 It at runtime makes a computation and assign it to a . 它在运行时使计算,并将其分配给a This is a meaning of runtime constant 这是运行时常量的意思

As you yourself note, that term is not used in the language specification etc. So; 如您自己所述,该术语未在语言规范等中使用。 blame that book! 怪那本书! I would call it a "readonly field", because that is what it is - where the definition of "readonly" here relates to the initializer/constructor, and is limited to regular code . 我将其称为“只读字段”,因为这就是它-这里“只读”的定义与初始化程序/构造函数有关,并且仅限于常规代码 For example, even readonly fields are changeable... 例如,即使是只读字段也可以更改...

// how to annoy your colleagues...
typeof(string).GetField("Empty").SetValue(null, " ");

(Note, this no longer works on recent CLR versions - the JIT presumably replaces the field-load with a ldstr - but it genuinely did for a very long time) (请注意,这不再适用于最新的CLR版本-JIT可能用ldstr代替了字段加载-但实际上确实做了很长时间)

(more genuine reasons to do this on objects relate to deserialization) (在对象上执行此操作的更多真正原因与反序列化有关)

A readonly variable can only be changed in its constructor and can be used on complex objects. 只读变量只能在其构造函数中更改,并且可以在复杂对象上使用。 A constant variable cannot be changed at runtime, but can only be used on simple types like Int, Double, String. 常量变量不能在运行时更改,只能在简单类型(如Int,Double,String)上使用。 Runtime constant is somewhat accurate, but confuses the issue, there are very explicit differences between a constant and a readonly, and so naming one similar to another is probably not a good idea, even though often they are used to the same purpose. 运行时常量在某种程度上是准确的,但是却使问题感到困惑,常量和只读之间存在非常明显的区别,因此,将一个相似的名称命名为另一个可能不是一个好主意,即使经常将它们用于相同的目的。

A quick summary of the differences here 这里的差异的简要总结

I would call readonly a "write once variable" , which is checked by the compiler, not at runtime. 我将readonly称为“一次写入变量” ,它由编译器而不是在运行时检查。 You could write the field using reflection, so it is not constant at runtime. 您可以使用反射来编写字段,因此它在运行时不是恒定的。

const vs readonly const vs readonly

This a complete resume comparison between const and readonly : 这是constreadonly之间的完整简历比较:

|-----------------------------------------|-----------------------------------------|
|              Constant Field             |             Read-only Field             |
|-----------------------------------------|-----------------------------------------|
| Compile-time constant                   | Run-time constant                       |
|-----------------------------------------|-----------------------------------------|
| Assigned to an expression evaluated at  | Assigned to any valid expression at     |
| compile time                            | runtime                                 |
|-----------------------------------------|-----------------------------------------|
| Assigned on declaration                 | Assigned on declaration or constructor  |
|-----------------------------------------|-----------------------------------------|
| Only number, Boolean or string          | Any data type                           |
|-----------------------------------------|-----------------------------------------|
| Always static                           | Optionally static                       |
|-----------------------------------------|-----------------------------------------|

Explanation 说明

  • Constants are static (no need to instantiate the class to access them). 常量是静态的(无需实例化类即可访问它们)。
  • Constants can only be assigned on declaration. 只能在声明时分配常量。
  • Constants are compile-time constant because they are assigned to an expression evaluated at compile time: when they changed, the project should be recompiled to use the new values. 常量是编译时常量,因为它们被分配给在编​​译时求值的表达式:更改常量时,应将项目重新编译为使用新值。
  • Read-Only Fields are variables in a class which hold a value that is initialized (only in the constructor or in the declaration) and then not changed. 只读字段是类中的变量,这些变量包含一个已初始化的值(仅在构造函数或声明中),并且未更改。
  • Read-Only Fields are Runtime constant because they can be assigned to any valid expression at runtime. 只读字段是运行时常量,因为可以在运行时将它们分配给任何有效的表达式。
  • A Read-Only Field apply to the instance of the object but not the property of that instance. 只读字段适用于对象的实例,但不适用于该实例的属性。 So other code can change the instance property of read-only field. 因此,其他代码可以更改只读字段的instance属性。
  • Read-Only Fields are optionally static (if you want to make them shared by all instances). 只读字段可以选择是静态的(如果要使所有实例共享它们)。

When to use const and when to use readonly ? 什么时候使用const和什么时候使用readonly

  • Constants are useful when they are of simple type and their values will never be changed. 当常量为简单类型且其值永远不会更改时, 很有用。
  • Read-Only Fields are useful when they are initialized from a source (file, database or other codes, ..etc.) but then they will not be changed. 从源 (文件,数据库或其他代码,.. etc。) 初始化只读字段时,该字段很有用,但随后将不会更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM