What does compile time 'const' mean?

2020-02-05 18:03发布

They say the difference between readonly and const is that const is compile-time (while readonly is run time). But what exactly does that mean, The fact that it's compile time? Everything gets compiled to byte code doesn't it?

标签: c#
6条回答
Fickle 薄情
2楼-- · 2020-02-05 18:36

One consequence of const being compile time is that changes to the const in one assembly does not get picked up automatically by other assemblies without recompiling them all.

Eg:

  1. Assembly A has public const of int = 10
  2. Assembly B refers to that const.
  3. Both compiled. Now Assembly A const changed to 20, redeployed.
  4. Assembly B not recompiled.

At runtime, Assembly B thinks the value of the const is still 10, not 20.

If it were readonly, it would pick up the new value.

查看更多
家丑人穷心不美
3楼-- · 2020-02-05 18:38

It just means that every instance of the member marked as const will be replaced with its value during compilation, while readonly members will be resolved at run-time.

查看更多
smile是对你的礼貌
4楼-- · 2020-02-05 18:50

Typically, a "compile-time constant" would refer to a constant literal value that the compiler would resolve. The code that the compiler generates will have the constnat value available as an immediate operand, instead of having to load it from memory.

查看更多
一纸荒年 Trace。
5楼-- · 2020-02-05 18:53

Although the answer that Julio provided is valid from the effects of setting a variable as a constant or a read only, there are a great deal of difference between the two declarations.

While many people simply state the obvious that the value of a constant is resolved at the compilations, while a read only value will be resolved only during the run time, the main point resides where the reference is quept.

Depending on the data type of the constant, it will be either replaced at the command evocation, or stored in the HEAP and referenced by a pointer.

For instance, the code:

const int x = 3;
int y = 3 * x;

may be resolved at the compilation time as simply:

int y = 3 * 3;

On the other hand a read only field is always stored on the STACK and referenced by a pointer.

查看更多
唯我独甜
6楼-- · 2020-02-05 18:54

A const can only be defined during its declaration. A readonly can be defined during its declaration or in a constructor. So a readonly variable can have different values according to the constructor used to initialize it.

查看更多
该账号已被封号
7楼-- · 2020-02-05 18:55

It means that const variables get written to the location they are referenced from. So, say you have an 2 libraries, one with a const variable:

// Library A
const int TEST = 1;

// Library B
void m ()
{
   Console.WriteLine(A.TEST);
}

The variable is actually written, at compile time, into B. The difference is, if you recompile A but not B, B will have the "old" value. This won't happen with readonly variables.

查看更多
登录 后发表回答