简体   繁体   中英

What is the difference between a static class and a namespace? (in C#)

The only difference I see is the fact that you can't use the "using staticClass" declaration.

Therefore, I'm wondering:

  1. Is there a real difference between a static class and a namespace?
  2. Is there a possibility to avoid having to rewrite the class name every time a member function is called? I'm thinking about something analogous to "using staticClass".

Yes, a static class is technically a type. It can have members (fields, methods, events). A namespace can only hold types (and it's not considered a "type" by itself; typeof(System) is a compile-time error).

There's no direct equivalent to adding a using directive for a namespace for a static class. You can, however, declare aliases:

using ShortName = ReallyReallyLongStaticClassName;

and use

ShortName.Member

when referring its members.

Additionally, you can use static classes to declare extension methods on other types and use them directly without referring to the class name explicitly:

public static class IntExtensions {
   public static int Square(this int i) { return i * i; }
}

and use it like:

int i = 2;
int iSquared = i.Square(); // note that the class name is not mentioned here.

Of course, you'll have to add a using directive for the namespace containing the class to use the extension method if the class is not declared in the root or current namespace.

Static class is still a class. It can contain methods, properties, etc. Namespace is just a namespace. It's just a helper to distinguish between class declarations with the same name.

Function can't live in a namespace alone, it belongs to a class.

Extensions is probably what you are looking for, if you need a static function without mentioning the name of the class.

public static class MathExtensions
{
 public static int Square(this int x)
 {
  return x * x;
 }
}
//...
// var hundredSquare = 100.Square();

另一个区别是命名空间可以跨越多个程序集,而类则不能。

As far as I understand, namespaces are a language feature only; they get removed by compilation. In other words, the .NET runtime does not "see" namespaces, just class names that happen to contain dots. For example, the String class in the System namespace is seen by the .NET runtime as a class named System.String , but there is no concept of namespace at all.

Static classes, however, are fully understood and managed by the .NET runtime. They are fully-fledged types and you can use reflection on them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM