代码之家  ›  专栏  ›  技术社区  ›  Paul Fryer

为什么在C#中使用global关键字?

  •  55
  • Paul Fryer  · 技术社区  · 15 年前

    我想知道你为什么要用 global:: 前缀。在以下代码中,ReSharper将其标识为冗余,并且可以删除:

    alt text

    3 回复  |  直到 8 年前
        1
  •  53
  •   Martin Liversage    15 年前

    最好在生成的代码中使用全局名称空间前缀。这样做是为了避免命名空间中存在类似命名类型的情况。

    System.Diagnostics.DebuggerNonUserCodeAttribute 在命名空间中 你会注意到ReSharper不再说 global::

        2
  •  67
  •   JaredPar    15 年前

    关键字 global:: 使编译器绑定从全局命名空间开始的名称,而不是当前上下文中的名称。当一个可绑定的成员存在于一个给定的上下文中,并且该上下文与全局成员具有相同的名称,并且需要全局成员时,就需要使用它。

    例如

    class Test {
      class System {}
      public void Example() {
        System.Console.WriteLine("here"); // Error since System binds to Test.System
        global::System.Console.WriteLine("here"); // Works
    }
    

    相应的MSDN页面还有几个示例(包括上面的示例)

        3
  •  2
  •   johnnyRose    9 年前