Deciding to make a C# class static

2019-05-10 07:59发布

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?

4条回答
Ridiculous、
2楼-- · 2019-05-10 08:16

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楼-- · 2019-05-10 08:22

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.

查看更多
孤傲高冷的网名
4楼-- · 2019-05-10 08:23

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.

查看更多
唯我独甜
5楼-- · 2019-05-10 08:24

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.

查看更多
登录 后发表回答