What is global::?

前端 未结 4 1710
盖世英雄少女心
盖世英雄少女心 2020-12-02 16:15

In C# I see global:: used quite often in auto-generated code. It is not something I have ever used myself so I don\'t know what the purpose is. Can someone ex

4条回答
  •  無奈伤痛
    2020-12-02 16:56

    The global:: namespace and its identifier is not what most people think. It is not a universal identifier of everything created in an application that lies outside one of your application's defined namespaces and which is attached to some global root.

    If you create a class or type outside your top level namespaces you would assume its automatically a part of the GLOBAL namespace and accessible by the global:: identifier in all files in your application or assembly. In fact those names are more often in that file's compiled LOCAL scope only, yet are accessible via the global:: identifier.

    If you create a top level class or namespace in an aspx.cs file it is accessible via global:: from the global namespace in that file. But if you type global:: in another file, that class and namespace doesn't exist in the global namespace. If you create that same class or namespace in a class.cs file however, those items are available to all other files via global:: and in the global namespace as well as that files local scope. Why?

    It turns out global:: is really a reference to top level LOCAL names under the file's scope as well as GLOBAL names shared by the assembly (like what might be compiled in your App_Code class files in a typical ASP.NET project).

    I found this very confusing and not consistent, since global:: implies access to top-level namespaces and types created in the application that are tied to the global namespace. Some like "System" are tied to the global namespace by default in all files, but custom ones may or may not be depending on the scope of that file. That is why the global identifier has a secondary role of resolving references to your local root scope names as well.

    You can test this by creating top level namespaces and classes in parts of your application then using global:: to see which ones it can access in the global namespace from different parts of your application and which ones it cannot. The one's it cannot access are clearly assigned to a "local global scope" in that file only, which global:: helps you access in naming conflicts.

提交回复
热议问题