以下是MSDN在何时使用静态类时要说的内容:
Run Code Online (Sandbox Code Playgroud)static class CompanyInfo { public static string GetCompanyName() { return "CompanyName"; } public static string GetCompanyAddress() { return "CompanyAddress"; } //... }使用静态类作为与特定对象无关的方法的组织单位.此外,静态类可以使您的实现更简单,更快,因为您不必创建对象来调用其方法.以有意义的方式组织类中的方法很有用,例如System命名空间中Math类的方法.
对我来说,这个例子似乎并没有涵盖静态类的很多可能的使用场景.在过去,我已经将静态类用于相关函数的无状态套件,但这就是它.那么,在什么情况下应该(而且不应该)将一个类声明为静态?
对不起这个问题没有学问的性质.如果有一个简单的答案,只需要一个解释链接就会让我感到高兴.
编程6个月后,我发现静态类对于存储适用于许多不同类的例程有些用处.这是我如何使用静态类的简化示例,它是一个用于将文本解析为各种内容的类
public static class TextProcessor
{
public static string[] GetWords(string sentence)
{
return sentence.Split(' ');
}
public static int CountLetters(string sentence)
{
return sentence.Length;
}
public static int CountWords(string sentence)
{
return GetWords(sentence).Length;
}
}
Run Code Online (Sandbox Code Playgroud)
我用这个明显的方式使用它
class Program
{
static void Main(string[] args)
{
string mysentence = "hello there stackoverflow.";
Console.WriteLine("mysentence has {0} words in it, fascinating huh??", TextProcessor.CountWords(mysentence));
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:为什么有必要将这些静态方法包装在静态类中?它似乎没有任何意义.有没有办法让我们可以将这些方法单独包装在一个类中?我知道封装是有益的,但我没有看到静态类包含静态方法的用法.有没有我风格或其他方面缺少的东西?我完全吠了一棵傻树吗?我想的太多了吗?