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

C# namespace alias - what#39;s the point?(C# 命名空间别名 - 有什么意义?)

本文介绍了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.TimerSystem.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# 命名空间别名 - 有什么意义?

基础教程推荐