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

标签 c# syntax keyword

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

最佳答案

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

但是请注意,当没有为类型指定 namespace 时,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!");
    }
}

关于c# - C#中global::keyword的用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2340355/

相关文章:

c# - 区别var和Type。为什么 var 在这里不起作用?

python - 对运算符表达式的结果调用函数? (掩码==instance_id).astype(np.uint8)

tags - 如何从文本中提取关键字(标签)

c# - 使用 Google Adwords API for .NET 获取特定关键字的每月搜索次数

java - 如何使用 OpenNLP 从给定文本中提取关键短语?

c# - 是否可以对未知的数据库表使用 Entity Framework ?

c# - 让 child 不受 parent 轮换的影响 Unity

c# - 在 "01234567890"中格式化 "012.345.678-90"的更好方法?

mysql - 需要将此 mysql 表与子字符串相加才能找到正确的值

c - "install"函数在 C 语法中意味着什么?