Singleton implementation laziness with static constructor

前端 未结 1 1531
夕颜
夕颜 2021-01-06 03:26

Jon Skeet suggests in his singleton implementation that if you require the maximum laziness for your singleton you should add a static constructor which will make the compil

相关标签:
1条回答
  • 2021-01-06 03:54

    When I call Singleton.Stub() the private constructor is not being hit, when I uncomment the static ctor private constuctor is always called.

    It's not clear what the value of which is here, but fundamentally you've got four cases:

    • Static constructor, Singleton.Stub called: type initializer is guaranteed to run
    • Static constructor, Singleton.Stub not called: type initializer is guaranteed not to run
    • No static constructor, Singleton.Stub called: type initializer may run, but isn't guaranteed to
    • No static constructor, Singleton.Stub not called: type initializer may run, but isn't guaranteed to

    The last two cases only differ in that if you change Singleton.Stub to use a static field, the third case becomes "type initializer is guaranteed to run".

    0 讨论(0)
提交回复
热议问题