C# namespace alias - what#39;s the point?(C# 命名空间别名 - 有什么意义?)
问题描述
人们会在何时何地使用命名空间别名
Where or when would 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# 命名空间别名 - 有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 命名空间别名 - 有什么意义?
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
