[英]What is the difference between a static class and a namespace? (in C#)
我看到的唯一区别是您不能使用“using staticClass”声明。
因此,我想知道:
是的, static
类在技术上是一种类型。 它可以有成员(字段、方法、事件)。 命名空间只能保存类型(并且它本身不被视为“类型”; typeof(System)
是编译时错误)。
没有直接等同于为静态类的命名空间添加using
指令。 但是,您可以声明别名:
using ShortName = ReallyReallyLongStaticClassName;
并使用
ShortName.Member
在提及其成员时。
此外,您可以使用静态类在其他类型上声明扩展方法并直接使用它们,而无需显式引用类名:
public static class IntExtensions {
public static int Square(this int i) { return i * i; }
}
并使用它:
int i = 2;
int iSquared = i.Square(); // note that the class name is not mentioned here.
当然,如果类未在根或当前命名空间中声明,您必须为包含该类的命名空间添加using
指令以使用扩展方法。
静态类仍然是一个类。 它可以包含方法、属性等。命名空间只是一个命名空间。 它只是区分同名类声明的帮手。
函数不能单独存在于命名空间中,它属于一个类。
如果您需要一个静态函数而不提及类的名称,那么扩展可能就是您正在寻找的。
public static class MathExtensions
{
public static int Square(this int x)
{
return x * x;
}
}
//...
// var hundredSquare = 100.Square();
另一个区别是命名空间可以跨越多个程序集,而类则不能。
据我了解,命名空间只是一种语言特性; 它们被编译删除。 换句话说,.NET 运行时不会“看到”命名空间,而只是碰巧包含点的类名。 例如, System
命名空间中的String
类被 .NET 运行时视为名为System.String
的类,但根本没有命名空间的概念。
然而,静态类完全由 .NET 运行时理解和管理。 它们是成熟的类型,您可以对它们使用反射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.