What is the usage of global:: keyword in C#?

主宰稳场 提交于 2019-12-04 08:51:18

问题


What is the usage of global:: keyword in C#? When must we use this keyword?


回答1:


Technically, global is not a keyword: it's a so-called "contextual keyword". These have special meaning only in a limited program context and can be used as identifiers outside that context.

global can and should be used whenever there's ambiguity or whenever a member is hidden. From 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);
    }
}

Note, however, that global doesn't work when no namespace is specified for the type:

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


来源:https://stackoverflow.com/questions/2340355/what-is-the-usage-of-global-keyword-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!