C#中global :: keyword的用法是什么?

时间:2010-02-26 08:35:07

标签: c# syntax keyword

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

1 个答案:

答案 0 :(得分:45)

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

只要存在歧义或隐藏成员,就可以并且应该使用

global。来自here

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!");
    }
}