开发者

Why have all static methods/variables in a non-static class?

I have come across a class which is non-static, but all the methods and variables are static. Eg:

public class Class1 {

    private 开发者_JAVA百科static string String1 = "one";
    private static string String2 = "two";

    public static void PrintStrings(string str1, string str2)
    {
       ...

All the variables are static across all instances, so there is no point having separate instances of the class.

Is there any reason to create a class such as this?


Was the class written back in the .NET 1.x days? Static classes didn't appear until C# 2.0.


No. Make it a static class.


No. Some people dont realise that classes themselves can be static, and so don't include in the class definition. This is useful because it provides better intellisense options and ensures that future methods are added statically.

This also implicitly seals the class.


Static class provide :

  • Contains only static members.

  • Cannot be instantiated.

  • Is sealed.

  • Cannot contain Instance Constructors.

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor.


No, if there are no instance members in the class then it should be static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜