C# 命名空间别名

编程入门 行业动态 更新时间:2024-10-24 04:32:36
本文介绍了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# 命名空间别名

本文发布于:2023-11-09 06:02:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571578.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:别名   空间

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!