How to return a static class instance in c#

后端 未结 5 2060
花落未央
花落未央 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:26

    There is no reason to return a instance to a static class ( If the class is static there is no instance ).

    You can access the class from everywhere, why returning a instance to it? I can't imagine any reason to do this.

    Static class usage

    To use a static class just write it like below:

    MyStaticClass.MyMethod();
    Int32 callCount = MyStaticClass.CallCount;
    

    As you can see it doesn't even make sense to declare a variable because this would just look like this:

    MyStaticClass msc = MyStaticClass.Instance();
    msc.MyMethod();
    Int32 callCount = msc.CallCount;
    

    If you want to have a shorter name you just can use:

     using MSC = MyNamespace.MyStaticClass;
    

提交回复
热议问题