Why do static methods need to be wrapped into a class?

守給你的承諾、 提交于 2019-12-05 03:19:06

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:

  • define a function outside a class or;
  • import a module the same way you import a namespace (with using)

VB.NET, F# and Nemerle actually allow you to declare modules and import them; what allows you to use their methods unqualified.

This is valid Nemerle:

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

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.

This post by eric lippert gives a pretty detailed explanation. I'm not sure if this guy "eric" knows what he's talking about or not though ;-)

It would be somewhat awkward to have methods just dangling around in a random namespace.

I suspect the answer is to provide "scope". Just because a method is static, doesn't mean it doesn't have a scope. It can still access other static private methods or member variables - and the class provides a "home" for these things to live in.

Static classes can also have static constructors that get called the first time a static method is used, so this provides the ability to set stuff up as needed.

It's more of an organizational design than anything to due with technical limitations.

xgencoder

already there are many threads on this topic which have enough information... you can find one here..

A static method is a method called in a single instance of a class that is created at run-time.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!