[英]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.我看到的唯一区别是您不能使用“using staticClass”声明。
Therefore, I'm wondering:因此,我想知道:
Yes, a static
class is technically a type.是的, static
类在技术上是一种类型。 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).命名空间只能保存类型(并且它本身不被视为“类型”; typeof(System)
是编译时错误)。
There's no direct equivalent to adding a using
directive for a namespace for a static class.没有直接等同于为静态类的命名空间添加using
指令。 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.当然,如果类未在根或当前命名空间中声明,您必须为包含该类的命名空间添加using
指令以使用扩展方法。
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.换句话说,.NET 运行时不会“看到”命名空间,而只是碰巧包含点的类名。 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.例如, System
命名空间中的String
类被 .NET 运行时视为名为System.String
的类,但根本没有命名空间的概念。
Static classes, however, are fully understood and managed by the .NET runtime.然而,静态类完全由 .NET 运行时理解和管理。 They are fully-fledged types and you can use reflection on them.它们是成熟的类型,您可以对它们使用反射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.