人们会在何时何地使用命名空间别名
using someOtherName = System.Timers.Timer;
在我看来,这只会给理解语言增加更多的困惑。
最佳答案
那是类型别名,不是命名空间别名;消除歧义很有用 - 例如,反对:
using WinformTimer = System.Windows.Forms.Timer;
using ThreadingTimer = System.Threading.Timer;
(ps: 感谢您选择Timer
;-p)
否则,如果您在同一文件中同时使用 System.Windows.Forms.Timer
和 System.Timers.Timer
,则必须继续提供全名(因为 Timer
可能会造成混淆)。
它还与 extern
别名一起使用,用于使用来自不同程序集的具有相同完全限定类型名称的类型 - 很少见,但有助于支持。
实际上,我可以看到另一种用途:当你想快速访问一个类型,但不想使用常规的 using
因为你不能导入一些冲突的扩展方法......有点令人费解,但是……这里有一个例子……
namespace RealCode {
//using Foo; // can't use this - it breaks DoSomething
using Handy = Foo.Handy;
using Bar;
static class Program {
static void Main() {
Handy h = new Handy(); // prove available
string test = "abc";
test.DoSomething(); // prove available
}
}
}
namespace Foo {
static class TypeOne {
public static void DoSomething(this string value) { }
}
class Handy {}
}
namespace Bar {
static class TypeTwo {
public static void DoSomething(this string value) { }
}
}
关于C# 命名空间别名 - 有什么意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/505262/