The using directive allows the use of a type defined in a namespace without specifying a fully qualified namespace for that type. Adding the global modifier to the using directive means that using will be applied to all files in the compilation (usually a project). The global using directive was added to C# 10. The syntax is:
The recommended practice is to put the global import in a separate file (one for each project), e.g. it can be named:GlobalUsings.csFile.
Microsoft official documentation introduction:The hyperlink login is visible.
We put the namespace referenced by Startup.cs into the GlobalUsings.cs file, remembering to add before usingglobalKeywords!! The code is as follows:
At this time, the compiler will report an error stating that "the function global using command is not available in C# 8.0, please use language version 10.0 or later", as shown in the figure below:
In this case, taking the ASP.NET Core 3.1 project as an example, you only need to double-click on the project (.csproj file) and add LangVersion to the Project-> PropertyGroup node, as shown in the following figure:
This sentence means that the project uses the syntax of C# 10 regarding C# language versioning:The hyperlink login is visible.
The file is not reported as an error, at the same timeStartup.cs The namespace referenced by the file is grayed out, as shown in the figure below:
We remove the references of Program.cs, Startup.cs, and then recompile the project as shown in the image below:
useILSpy_binaries_7.2.0.6702-preview2The resulting WebApplication1.dll file is decompiled as shown in the following image:
The startup file still has using references, and no GlobalUsings.cs files are generated, so global using is just syntax sugar, which simplifies some tedious programming work and greatly improves work efficiency.
.NET 6Implicit namespacesReferences are also achieved by using the global using feature.
Currently, different default namespaces are added for different SDK types, and the existing ones are as follows:
For Microsoft.NET.Sdk, the default namespace is as follows:
For Microsoft.NET.Sdk.Web:
For Microsoft.NET.Sdk.Worker:
If you want to disable implicit namespace references, you can disable this feature entirely via DisableImplicitNamespaceImports, as follows:
If you just want to disable references to Microsoft.NET.Sdk.Web, you can configure the DisableImplicitNamespaceImports_Web as follows:
Let's create a new .NET 6.0 console project for testing, and the whole project only has Program.cs one file, as shown in the figure below:
ConsoleApp1.csproj is configured as follows:
Where is the global using directive? Open the obj directory (which houses the intermediate temporary files generated during the compilation process) and find it in the Debug\net6.0 directoryConsoleApp1.GlobalUsings.g.csFile:
ConsoleApp1.GlobalUsings.g.cs files are automatically generated based on the project's ImplicitUsings property settings.
(End)
|