How to return a static class instance in c#

后端 未结 5 2055
花落未央
花落未央 2021-01-17 21:48

I would like to get an instance of a static class, but I can’t seem to do this without implementing a singleton wrapper on a non-static class– is this possible, or am I miss

5条回答
  •  灰色年华
    2021-01-17 22:37

    There is no such thing as an instance of a static class. The singleton pattern simply returns the same instance of a class to repeated requests.

    You may be getting confused by:

    private static MyClass _myInstance;
    

    This simply means that there will be a single instance of that particular object among all objects instantiated of the type that have _myInstance as a member.

    A few notes:

    • The this keyword is not valid in a static member
    • If you have a static class then all members have to be static and so this will never be valid
    • A Singleton class cannot be a static class
    • Singletons declare a single static member to help ensure that only a single instance of that class exists
    • Note that a static reference to an object does not make the object static. Only the reference is static

    Further reading: Jon Skeet has an excellent write up on implemeting Singletons in C# In Depth. I would suggest reading and studying this article until you grok it. It is quite good.

提交回复
热议问题