C#名称空间别名-重点是什么? [英] C# namespace alias - what's the point?
问题描述
我一直在尝试学习有关C#语言的更多信息,但是我还没有看到有人会使用命名空间别名的情况,例如
I have been trying to learn more about the C# language, but I haven't been able to see a situation where one would use namespace aliasing like
using someOtherName = System.Timers.Timer;
在我看来,这只会增加理解该语言的困惑.
It seems to me that it would just add more confusion to understanding the language.
有人可以解释吗?
推荐答案
这是类型别名,而不是名称空间别名;消除歧义很有用-例如,针对:
That is a type alias, not a namespace alias; it is useful to disambiguate - for example, against:
using WinformTimer = System.Windows.Forms.Timer;
using ThreadingTimer = System.Threading.Timer;
(ps:感谢您选择Timer
;-p)
(ps: thanks for the choice of Timer
;-p)
否则,如果在同一个文件中同时使用System.Windows.Forms.Timer
和System.Timers.Timer
,则必须继续提供全名(因为Timer
可能会造成混淆).
Otherwise, if you use both System.Windows.Forms.Timer
and System.Timers.Timer
in the same file you'd have to keep giving the full names (since Timer
could be confusing).
它还具有extern
别名,可用于使用来自不同程序集的具有完全限定类型名称的相同类型-很少见,但受支持很有用.
It also plays a part with extern
aliases for using types with the same fully-qualified type name from different assemblies - rare, but useful to be supported.
实际上,我可以看到另一种用法:当您想快速访问类型但又不想使用常规的using
时,因为您不能导入一些冲突的扩展方法...有点令人费解,但是...这是一个例子...
Actually, I can see another use: when you want quick access to a type, but don't want to use a regular using
because you can't import some conflicting extension methods... a bit convoluted, but... here's an example...
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#名称空间别名-重点是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!