Deciding to make a C# class static

2019-05-10 08:02发布

问题:

If I have a Utilities.cs class in C#, which contains only static methods

e.g.

public static string DoSomething()
{
    return "something";
}

Should I make the class itself static?

public static Utilities()
{
    ...

Does making the class static have any advantages?

回答1:

Yes you should. It stops people from instantiating the class when they shouldn't, and makes the purpose of the class clearer. Have a read of the MSDN page for more information.

You also need to mark the class as static if you want to add Extension Methods

You should think carefully about utility classes. Think whether the methods truly belong there, or if there's a more OO way of doing it.

Also look at this question and the answer by Jon Skeet.



回答2:

The main advantage is that it makes your design intent clearer, and enforces those intents. For instance you cannot inherit from a static class (i.e. specialize it), and you cannot make an instance of it (it is in effect a singleton). These would both be design intents of your utilities class.

However, static classes and methods should be used with caution, as it makes it difficult to vary behaviour of your program. Static classes and methods are very concrete and cannot be (easily) substituted, as would be the case if you used interfaces and constructor injection. Static classes and members can however be useful, but rarely. Overuse of statics make your software less flexible, and more difficult to test.



回答3:

Yes, you should make it static. Making it static prevents it from being instanced. It's primarily designed to tell the person using the class that it only contains static methods, which helps readability.



回答4:

Only that static class can not contain non-static members, so preventing you from accidentally adding them. Also as mentioned in Ray's answer, it will make your code clearer.