繁体   English   中英

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

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

C#中global:: keyword的用法是什么? 什么时候必须使用此关键字?

从技术上讲, 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!");
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM