C#中global::关键字的用途是什么?

31

global::关键字在C#中的使用是什么?我们何时需要使用这个关键字?

1个回答

46

从技术上讲,global不是关键字:它是所谓的“上下文关键字”。这些仅在有限的程序上下文中具有特殊含义,并且可以在该上下文之外用作标识符。

只要存在歧义或成员被隐藏,就应该使用global。来自这里

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()
    {
        // Error  Accesses TestApp.Console
        Console.WriteLine(number);
        // Error either
        System.Console.WriteLine(number);
        // This, however, is fine
        global::System.Console.WriteLine(number);
    }
}

请注意,当未为类型指定命名空间时,global 无法使用:
// See: no namespace here
public static class System
{
    public static void Main()
    {
        // "System" doesn't have a namespace, so this
        // will refer to this class!
        global::System.Console.WriteLine("Hello, world!");
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接