Why use the global keyword in C#?

前端 未结 3 1493
感动是毒
感动是毒 2020-12-25 09:41

I would like to understand why you might want to use the global:: prefix. In the following code, ReSharper is identifying it as redundant, and able to be remove

相关标签:
3条回答
  • 2020-12-25 10:12

    "The global contextual keyword, when it comes before the :: operator, refers to the global namespace, which is the default namespace for any C# program and is otherwise unnamed."

    Source: https://msdn.microsoft.com/en-us/library/cc713620.aspx

    0 讨论(0)
  • 2020-12-25 10:16

    It is best to use the global namespace prefix in generated code. This is done to avoid situations where a similar named type exists in your namespace.

    If you create a type named System.Diagnostics.DebuggerNonUserCodeAttribute inside your namespace you will notice that ReSharper no longer says that the global:: is not needed. The code generator simply wants to avoid any collisions with the names of your own types.

    0 讨论(0)
  • 2020-12-25 10:28

    The keyword global:: causes the compiler to bind names starting in the global namespace as opposed to in the current context. It's needed in places where a bindable member exists in a given context that has the same name as a global one and the global one is desired.

    For example

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

    The corresponding MSDN page has a few more examples (including the one above)

    • http://msdn.microsoft.com/en-us/library/c3ay4x3d.aspx
    0 讨论(0)
提交回复
热议问题