Using Static constructors to create a singleton in C#

后端 未结 3 723
既然无缘
既然无缘 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:25

    Your code isn't building a singleton. It's creating an instance of Foo, and presumably anyone else could too - which means it isn't a singleton.

    You've created a single instance which is referred to by a static variable in ServiceFactory, but that's not the same thing.

    Unless you have some class which you've restricted so that there can only ever be one instance of it, you don't have a singleton. You may have a factory pattern, a cache, whatever - but you don't have a singleton.

    Now what you've got is equivalent to this:

    static Foo container = new Foo();
    static ServiceFactory()
    {
    }
    

    ... and I'm not sure why you think your version is simpler than the above. If you do want to actually create a singleton, you're going to need a private constructor for whatever class you're trying to turn into a singleton. At that point, you've basically got my fourth example, so again I'm not sure where you think you're making things simpler.

    Of course, you may not need a static constructor at all - it depends on how precise you need the timing to be. (Read my article on beforefieldinit for more details, along with my blog post about the CLR v4 changes.)

提交回复
热议问题