'Static readonly' vs. 'const'

前端 未结 18 2891
旧巷少年郎
旧巷少年郎 2020-11-22 04:07

I\'ve read around about const and static readonly fields. We have some classes which contain only constant values. They are used for various things

18条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 04:57

    A static readonly field is advantageous when exposing to other assemblies a value that might change in a later version.

    For instance, suppose assembly X exposes a constant as follows:

    public const decimal ProgramVersion = 2.3;
    

    If assembly Y references X and uses this constant, the value 2.3 will be baked into assembly Y when compiled. This means that if X is later recompiled with the constant set to 2.4, Y will still use the old value of 2.3 until Y is recompiled. A static readonly field avoids this problem.

    Another way of looking at this is that any value that might change in the future is not constant by definition, and so should not be represented as one.

提交回复
热议问题