Static classes in c#

前端 未结 8 709
别那么骄傲
别那么骄傲 2021-01-18 03:09

In answering this question (https://stackoverflow.com/questions/352317/c-coding-question#352327), it got me wondering...

Is there any danger in regarding a static cl

相关标签:
8条回答
  • 2021-01-18 03:47

    The only thing that seems immediately apparent to me is that a static class is basically just a collection of scoped functions (explicitly avoiding "methods" here) and a singleton is still something you can instantiate, even if you can only have 1. 1 > 0.

    You can pass a singleton as an argument to something that expects an object of a certain interface, you cannot pass a static class anywhere (except through some reflection trickery)

    0 讨论(0)
  • 2021-01-18 03:47

    As Robert said before, the initialization is a main disadvantage of a static class. The static class will usually be initialized lazily, at the last possible moment. However, you lose control over the exact behavior and static constructors are slow.

    Often static classes are used to hold global data. And global data creates an implicit dependency between your other objects / classes. So you must be carful when changing this "global object". Can break your application.

    0 讨论(0)
  • 2021-01-18 03:58

    In context of singleton implementation there is no any danger, I think. I often do the same, imlementing singletone via static class. Logically, object reference isn't necessary if it's alone and unique.

    0 讨论(0)
  • 2021-01-18 03:59

    As Robert Gould pointed out, you loose control over construction. You will also get construction issues which are a lot more obscure. Static classes quickly end up with static initializer blocks. These blocks get called the first time someone references your type, and this order may not be as well defined as you like to think. So the run-order of these static initializers may change without you planning so, and can cause strange bugs.

    0 讨论(0)
  • 2021-01-18 04:00

    Not sure about C#, but in C++ a static Object will get initialized when it gets initialized, and you have no direct control over that (especially in multithreaded apps). So you need a function to call your object, not just call it directly (unless you want unportable code)

    0 讨论(0)
  • 2021-01-18 04:06

    The main danger that I can see with static classes is that they are much harder to mock when writing unit tests. With a singleton you can create it in such a way that you can inject a different class in its place that does test specific functionality, with a static class this is not so easy.

    0 讨论(0)
提交回复
热议问题