我看到的唯一区别是你不能使用"using staticClass"声明.所以我想知道:
(1)静态类和命名空间之间是否存在真正的区别?
(2)每次调用成员函数时是否有可能避免重写类名?我正在考虑类似于"使用staticClass"的东西.
Meh*_*ari 31
是的,一个static类在技术上是一种类型.它可以有成员(字段,方法,事件).命名空间只能包含类型(并且它本身不被视为"类型"; typeof(System)是编译时错误).
没有直接的等价于using为静态类添加命名空间的指令.但是,您可以声明别名:
using ShortName = ReallyReallyLongStaticClassName;
Run Code Online (Sandbox Code Playgroud)
并使用
ShortName.Member
Run Code Online (Sandbox Code Playgroud)
在提及其成员时.
此外,您可以使用静态类来声明其他类型的扩展方法,并直接使用它们而无需显式引用类名:
public static class IntExtensions {
public static int Square(this int i) { return i * i; }
}
Run Code Online (Sandbox Code Playgroud)
并使用它像:
int i = 2;
int iSquared = i.Square(); // note that the class name is not mentioned here.
Run Code Online (Sandbox Code Playgroud)
当然,using如果未在根或当前命名空间中声明类,则必须为包含类的命名空间添加指令以使用扩展方法.
静态类仍然是一个类.它可以包含方法,属性等.命名空间只是一个命名空间.它只是区分具有相同名称的类声明的帮助器.
函数不能单独存在于命名空间中,它属于一个类.
如果您需要静态函数而不提及类的名称,那么扩展可能就是您正在寻找的.
public static class MathExtensions
{
public static int Square(this int x)
{
return x * x;
}
}
//...
// var hundredSquare = 100.Square();
Run Code Online (Sandbox Code Playgroud)
据我了解,命名空间只是一种语言特性;它们被编译删除。换句话说,.NET 运行时不会“看到”命名空间,而只是碰巧包含点的类名。例如,命名空间中的String类System被 .NET 运行时视为名为 的类System.String,但根本没有命名空间的概念。
然而,静态类完全由 .NET 运行时理解和管理。它们是成熟的类型,您可以对它们使用反射。
| 归档时间: |
|
| 查看次数: |
2746 次 |
| 最近记录: |