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

问题描述:

我很想知道const变量和静态变量之间的区别。

I am eager to know the difference between a const variable and a static variable.

据我所知,const也是静态的,无法在const*问实例变量就像static一样,那么它们之间有什么区别?

As far as I know a const is also static and can not be accessed on instance variable that's same like static , then what is the difference between them ?

请解释一下...

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).