Visual Studio 代码错误无法将受保护的访问修饰符显式分配给未在命名空间中定义的 class

Visual Studio Code error can not explicitly assign protected access modifier to a class which is not defined in a namespace

我在 VSCode 版本 1.63.2 中编写 C#,问题是;

class ClassTwo Elements defined in a namespace cannot be explicitly declared as private, protected, protected internal, or private protected [test]csharp(CS1527)

我现在没有在我的 .cs 文件中声明任何命名空间。起初,我声明了一个命名空间,然后将其删除,但错误仍然存​​在。我尝试的是重命名 class(它可以工作,使用不同的 class 名称我不会遇到这个问题),然后我尝试删除 class 文件并重新创建它同名(这不起作用)。我有一个名为“test”的项目,其中包含两个 classes 和两个同名的 .cs 文件,一个名为 ClassOne,另一个名为 ClassTwo。

ClassOne.cs

namespace test
{
    protected class ClassOne
    {
        
    }
}

ClassTwo.cs

protected class ClassTwo
{
    
}

test.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net5.0</TargetFramework>
  </PropertyGroup>

</Project>

问题截图;

problem

您不能在命名空间中声明 privateprotected class。 类 是 publicinternal(嵌套的 class 除外)。这个问题与 VS Code 无关,它只是编译器告诉你做错了。

引自the documentation

Classes that you declare directly within a namespace, not nested within other classes, can be either public or internal. Classes are internal by default.

编辑 2

现在您发布了代码,我们终于可以了解您的问题并为您提供答案。

您使用的是默认使用 C# 9 的 .NET 5。因此,我在第一个 EDIT 部分中写下的答案是不相关的。

在 C# 中,当您不在文件中声明任何名称空间时,您的 class 默认添加到 全局名称空间

The global namespace is the namespace that contains namespaces and types that are not declared inside a named namespace.

有关详细信息,请参阅 this page

假设您正在更正错误并将 class 更改为 publicinternal,然后您可以像这样使用它

var myTwoObject = new global::ClassTwo();

编辑

我保留这部分只是因为它是有用的信息,但是由于您随后发布了您的代码,我们现在可以知道您不在 C# 10 中,因此这不是正确的答案

根据您的评论,我现在了解到您一定已经创建了一个 .NET 6 控制台应用程序

默认情况下,.NET 6 中的控制台应用程序是使用从 C# 10 开始有效的新模板生成的

查看文档New C# templates generate top-level statements

您可以通过

访问您的class

引自该文档:

The term top-level statements means the compiler generates the namespace, class, and method elements for your main program. You can look at the code for the new application and imagine that it contains the statements inside the Main method generated by earlier templates.

就是说即使你不声明命名空间,它仍然是在编译时生成的。考虑命名空间 implicit 就像 Implicit using directives.