What is the difference between Const and Static in C#?

前端 未结 5 1336
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 10:19

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

As far as I know a const is also static and can not be accessed on instance variabl

5条回答
  •  孤街浪徒
    2020-12-08 10:49

    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.

    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.

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

提交回复
热议问题