'Static readonly' vs. 'const'

前端 未结 18 2594
旧巷少年郎
旧巷少年郎 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 05:08

    public static readonly fields are a little unusual; public static properties (with only a get) would be more common (perhaps backed by a private static readonly field).

    const values are burned directly into the call-site; this is double edged:

    • it is useless if the value is fetched at runtime, perhaps from config
    • if you change the value of a const, you need to rebuild all the clients
    • but it can be faster, as it avoids a method call...
    • ...which might sometimes have been inlined by the JIT anyway

    If the value will never change, then const is fine - Zero etc make reasonable consts ;p Other than that, static properties are more common.

提交回复
热议问题