C# 命名空间别名 - 有什么意义?

标签 c# namespaces

人们会在何时何地使用命名空间别名

 using someOtherName =  System.Timers.Timer;

在我看来,这只会给理解语言增加更多的困惑。

最佳答案

那是类型别名,不是命名空间别名;消除歧义很有用 - 例如,反对:

using WinformTimer = System.Windows.Forms.Timer;
using ThreadingTimer = System.Threading.Timer;

(ps: 感谢您选择Timer ;-p)

否则,如果您在同一文件中同时使用 System.Windows.Forms.TimerSystem.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/

相关文章:

c# - 从 xml 文件调用方法

r - 在 R 的全局环境中使用来自包函数的动态加载的 dll

ruby-on-rails - 在 Controller 中找不到 namespace 内的 Ruby on Rails 模型

kubernetes - 一个 Metricbeat Pod 来监控多个 RabbitMQ 容器

c# - C#中的父子继承管理

c# - 使用 XDocument 解析 XML

javascript - 获取 div javascript 文件中的按钮

c# - 信号量和 Web 套接字

c# - 如何获取特定角色的用户列表?

c++ - 具有排序问题的结构的静态数据成员的命名空间