为什么需要将静态方法包装到类中?

Epi*_*ody 8 c# static-methods

对不起这个问题没有学问的性质.如果有一个简单的答案,只需要一个解释链接就会让我感到高兴.

编程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)

我的问题是:为什么有必要将这些静态方法包装在静态类中?它似乎没有任何意义.有没有办法让我们可以将这些方法单独包装在一个类中?我知道封装是有益的,但我没有看到静态类包含静态方法的用法.有没有我风格或其他方面缺少的东西?我完全吠了一棵傻树吗?我想的太多了吗?

Jor*_*dão 7

在C#中,任何方法都必须在类中声明.这就是指定语言的方式.

静态类实际上更类似于模块而不是类,所以我也认为你应该能够:

  • 定义类外的函数或;
  • 导入模块的方式与导入命名空间的方式相同(带using)

VB.NET,F#和Nemerle实际上允许你声明模块并导入它们; 什么允许你使用他们的方法不合格.

这是有效的Nemerle:

using System.Console; // import static methods in the Console class
class Hello {
  static Main() : void {
    WriteLine("Hello, world!"); // unqualified access!
  }
}
Run Code Online (Sandbox Code Playgroud)

另外,看看扩展方法,它们可能允许您以不同的方式"解决"这个问题.在你的方法TextProcessor乞讨string扩展方法.