问题
This MSDN article states that static classes should be declared as sealed and abstract. I was under the impression that static classes were already sealed. Why would you also need to declare a static class as sealed?
回答1:
I think the pertinent bit from that article is:
"Do declare static classes as sealed and abstract, and add a private instance constructor, if your programming language does not have built-in support for static classes."
Remember, the .NET framework supports a lot of different languages.
回答2:
C# v1 did not allow 'static' keyword on class. So if you have a class with only static methods, it was suggested to declare it 'sealed', 'abstract' and make constructor private. This means that no one can instantiate your class or try to inherit from it. [It doesn't make sense to inherit from a class which has only static methods.]
C# v2 allowed the static keyword on a class so you don't have to use the above trick to enforce correct usage.
回答3:
- One of the effects of marking a class as
abstract
is that it cannot be instantiated. - One of the effects of marking a class as
sealed
is that is cannot be inherited.
That's what a static
class actually is -- a class that cannot be instantiated and that cannot be inherited.
So the article doesn't state you should mark your static classes as abstract
and sealed
additionally, but this is the way how static classes are represented in IL.
(Other languages may allow you to do this if they do not have a static
keyword, although I doubt it, because an abstract sealed
class doesn't make a lot of sense semantically.)
回答4:
It appears to be saying that declaring a class as sealed and abstract with a private constructor is an alternative to the static class if the language does not support static classes.
来源:https://stackoverflow.com/questions/1268983/why-declare-static-classes-as-sealed-and-abstract-in-c