命名空间别名限定符 (::)

命名空间别名限定符 (::) 用于查找标识符。它通常放置在两个标识符之间,例如:

global::System.Console.WriteLine("Hello World");

命名空间别名限定符可以是 global这将调用全局命名空间中的查找,而不是在别名命名空间中。

那到底在什么情况下使用呢?

当我们自定义的命名空间与.NET Framework系统命名空间有冲突时,而我们又要调用系统命名空间中的类。

例如,在下面的代码中,ConsoleSystem 命名空间中解析为 TestApp.Console 而不是 Console 类型。
using System;
class TestApp
{
    // Define a new class called 'System' to cause problems.
    public class System { }

    // Define a constant called 'Console' to cause more problems.
    const int Console = 7;
    const int number = 66;

    static void Main()
    {
        // The following line causes an error. It accesses TestApp.Console,
        // which is a constant.
        //Console.WriteLine(number);
    }
}

由于类 TestApp.System 隐藏了 System 命名空间,因此使用 System.Console 仍然会导致错误:

System.Console.WriteLine(number);

但是,可以通过使用 global::System.Console 避免这一错误,如下所示:

global::System.Console.WriteLine(number);

 

虽然,并不推荐创建名为 System 的命名空间,您不可能遇到出现此情况的任何代码。但是,在较大的项目中,很有可能在一个窗体或其他窗体中出现命名空间重复。在这种情况下,全局命名空间限定符可保证您可以指定根命名空间。

 

在此示例中,命名空间 System 用于包括类 TestClass,因此必须使用 global::System.Console 来引用 System.Console 类,该类被 System 命名空间隐藏。而且,别名 colAlias 用于引用命名空间 System.Collections;因此,将使用此别名而不是命名空间来创建 System.Collections.Hashtable 的实例。

using colAlias = System.Collections;
namespace System
{
    class TestClass
    {
        static void Main()
        {
            // Searching the alias:
            colAlias::Hashtable test = new colAlias::Hashtable();

            // Add items to the table.
            test.Add("A", "1");
            test.Add("B", "2");
            test.Add("C", "3");

            foreach (string name in test.Keys)
            {
                // Searching the global namespace:
                global::System.Console.WriteLine(name + " " + test[name]);
            }
        }
    }
}


 

作者:邹毅
如果觉得本文让你有所收获,请键点击右下角的 推荐 按钮
本文版权归作者和博客园共有,欢迎转载,但必须保留原文连接。

原文地址:https://www.cnblogs.com/joey0210/p/2671657.html