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# 命名空间别名 - 有什么意义?
基础教程推荐
- 从 C# 控制相机设备 2022-01-01
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 将数据集转换为列表 2022-01-01
