c# - C# const 成员如何在内存中分配?

标签 c# memory-management constants

<分区>

问题的标题是不言自明的。我想知道声明为 const 的成员对于该类的所有实例是单例的还是每个实例都有自己的副本。

我读过一些关于 const 的问题,但其中大部分是指方法中的 const 变量。

最佳答案

C# 常量在公共(public)语言指令中被实现为具有 literal 约束的字段。查找 ECMA-335 §I.8.6.1.2 提供了明确的答案(强调我的):

The literal constraint promises that the value of the location is actually a fixed value of a built-in type. The value is specified as part of the constraint. Compilers are required to replace all references to the location with its value, and the [Virtual Execution System] therefore need not allocate space for the location. This constraint, while logically applicable to any location, shall only be placed on static fields of compound types. Fields that are so marked are not permitted to be referenced from CIL (they shall be in-lined to their constant value at compile time), but are available using reflection and tools that directly deal with the metadata.

好了,编译器必须将 const 字段的值直接复制到指令流中(通常使用 ldc.* 指令)。它们不存在于可引用的位置,但需要在元数据中并通过反射可用。它们可以像静态字段一样实现,但不是必须的。

关于c# - C# const 成员如何在内存中分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23529592/

相关文章:

c# - 像谷歌地方一样切换按钮

c# - 哈希整数数组

c# - 通过 for 语句循环遍历 System.Collections.Generic.Dictionary

c - 手动递增指针

c++ - 在 C++ 中更改 static const int 的值

c++ - 将数组的大小设置为从另一个常量除法得出的 const 的值

c# - System.Data.Entity 中不存在基础结构

memory-management - ehcache 是否保留(分配)使用 maxBytesLocalHeap 设置的堆内存?

objective-c - 如何通过重用单个 viewcontroller 加载 xibs 并处理内存警告?

c# - 存储我的程序使用的一组常量的最佳方法是什么?