Singleton implementation laziness with static constructor

耗尽温柔 提交于 2019-11-30 22:11:04

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!