31

global::C#中关键字的用途是什么?我们什么时候必须使用这个关键字?

4

1 回答 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!");
    }
}
于 2010-02-26T08:36:48.840 回答