'Static readonly' vs. 'const'

前端 未结 18 2602
旧巷少年郎
旧巷少年郎 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

    Another difference between declaring const and static readonly is in memory allocation.

    A static field belongs to the type of an object rather than to an instance of that type. As a result, once the class is referenced for the first time, the static field would "live" in the memory for the rest of time, and the same instance of the static field would be referenced by all instances of the type.

    On the other hand, a const field "belongs to an instance of the type.

    If memory of deallocation is more important for you, prefer to use const. If speed, then use static readonly.

提交回复
热议问题