且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#中的Const和Static有什么区别?

更新时间:2022-05-24 03:37:15

const 字段只能保存值类型或 System.String 。它们必须在编译时是不变的且可解析的。

const fields can only hold value types or System.String. They must be immutable and resolvable at compile-time.

静态只读字段通常可以保存引用类型,其中(字符串除外)只能在运行时创建。这些可以(但不应该)是可变类型;唯一不能更改的是引用本身。

static readonly fields can and generally do hold reference types, which (other than strings) can only be created at runtime. These can (but shouldn't) be mutable types; the only thing that cannot change is the reference itself.

如果您需要维护引用类型的常量实例集,则通常使用一组实例公共静态只读字段的集合,例如 System.Drawing.SystemColors

If you need to maintain a "constant" set of instances that are reference types, you generally do it with a set of public static readonly fields, such as the members of System.Drawing.SystemColors.

最后但并非最不重要的是,初始化 readonly 字段可以推迟到构造函数执行后执行,这意味着即使只能将其写入一次,也不必始终使用完全相同的方法对其进行初始化值。用 const 声明的真实常量只能有一个值(在编译时指定)。

Last but not least, initialization of a readonly field can be deferred until the execution of a constructor, which means that it even though it can only be written to once, it does not always have to be initialized with the exact same value. True constants declared with const can only ever have a single value (specified at compile time).