问题描述
对不起,这个问题的本质没有学问。如果有一个简单的答案,只是一个说明链接会让我更乐意。
Sorry for the unlearned nature of this question. If there's a simple answer, just a link to an explanation will make me more than happy.
6个月的编程后,我发现静态类是有些有用的存储例程适用于许多不同的类。下面是我如何使用静态类一个简单的例子,它是文本分析到不同的东西。
After 6 months programming I find static classes to be somewhat useful for storing routines that apply to many different classes. Here's a simplified example of how I use static classes, it's a class for parsing text into various things
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;
}
}
和我明显的方式使用像
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();
}
}
我的问题是:为什么有必要把它们包装在静态类的静态方法?
这似乎起不到任何作用。有没有一种方法,我可以对自己的这些方法不是包裹在一个班?我知道,封装是有益的,但我没有看到包裹在静态类的静态方法的使用。是否有我丢失的东西曲风或以其他方式?我是不是完全吠叫了一个愚蠢的树?我是不是想得太多了?
My question is: Why is it necessary to wrap these static methods in a static class?It seems to serve no purpose. Is there a way I can have these methods on their own not wrapped in a class? I know encapsulation is beneficial but I don't see the use for static methods wrapped in static class. Is there something I am missing stylistically or otherwise? Am I completely barking up a silly tree? Am I thinking too much?
推荐答案
在C#中,任何方法都有一个类的内部声明。这就是语言是多么规定。
In C#, any method has to be declared inside a class. That's just how the language is specified.
一个静态类其实更多的比一类,所以我也想你应该能够之一:
A static class is actually more akin to a module than a class, so I too think you should be able to either:
- 定义一个函数在类外部;
- 导入一个模块导入一个命名空间(与<$ C $以同样的方式C>使用)
- define a function outside a class or;
- import a module the same way you import a namespace (with
using
)
VB.NET,F#和Nemerle实际上允许您声明模块和导入;是什么让你用自己的方法,不合格的
VB.NET, F# and Nemerle actually allow you to declare modules and import them; what allows you to use their methods unqualified.
这是有效Nemerle:
This is valid Nemerle:
using System.Console; // import static methods in the Console class
class Hello {
static Main() : void {
WriteLine("Hello, world!"); // unqualified access!
}
}
此外,看一看的的,他们可能允许你解决这一以不同的方式。在这些方法的 TextProcessor
是乞讨的是字符串
扩展方法。
Also, take a look at extension methods, they might allow you to "solve" this in a different way. The methods in your TextProcessor
are begging to be string
extension methods.
这篇关于静态方法为什么需要被包装成一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!