C#/.NET + VisualStudio,命名空间问题

C#/.NET + VisualStudio, namespace problem

我开始学习C#/.NET/VisualStudio (2022),遇到这个奇怪的问题; System 中的所有 methods/classes 及其嵌套命名空间似乎都可用 没有 完整路径或在开头使用指令。

例如下面的例子编译得很好:

// Program.cs
namespace MyApp
{
    internal class Program
    {
        static void Main()
        {
            Console.WriteLine("Hello World!"); //System.Console
        }

        static HttpClient client = new HttpClient(); //System.Net.Http.HttpClient
    }
}

为什么会发生这种情况,我能否以某种方式禁用此行为?

您正在使用 implicit global usings。将 .csproj 文件中的行更改为

<ImplicitUsings>enable</ImplicitUsings>

<ImplicitUsings>disable</ImplicitUsings>

如果您使用的是 .NET 6,这很可能来自名为“隐式使用”的新功能。根据您的项目类型,某些名称空间会自动包含在内。例如,默认的控制台应用程序模板隐式包含以下命名空间:

  • 系统;
  • System.IO;
  • System.Collections.Generic;
  • System.Linq;
  • System.Net.Http;
  • System.Threading;
  • System.Threading.任务;

您可以通过在项目文件中包含以下内容来禁用此功能:

<PropertyGroup>
   <ImplicitUsings>disable</ImplicitUsings>
</PropertyGroup>

有关于此功能和“全局使用”的更多文档in this Microsoft documentation.