Using Static constructors to create a singleton in C#

后端 未结 3 726
既然无缘
既然无缘 2021-01-25 18:11

I\'ve been looking at the article on creating static constructors in c# here:

http://csharpindepth.com/Articles/General/Singleton.aspx

Now, one option he doesn\'

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-25 18:35

    The question of the day is this: do you want lazy instantiation or not? If you do not need lazy instantiation and are perfectly fine with on-load instantiation, feel free to use the paradigm you have, or even use this somewhat less verbose version:

    public static class ServiceFactory
    {
        private static readonly container = new Foo();
        public static Instance { get { return container; } }
    }
    

    Both work fine and are perfectly valid -- as long as you don't need lazy. If you need lazy, use the Fifth version pointed out in the article.

提交回复
热议问题