C# 只有一个编译单元可以有顶级语句

问题描述 投票:0回答:3

我刚刚开始学习 C#,我创建了 C# 控制台应用程序。为了理解这些概念,我观看了 how to setup vs code for c#

的视频

当我在 VS code 终端中运行

dotnet new console
命令时,它会创建一个包含
Program.cs
文件的新项目。

在视频中,

Program.cs
文件是这样的

// Program.cs
using System;
namespace HelloWorld
{
  class Program
  {
    static string Main(string[] args)
    {
      Console.WriteLine("Hello, World!");
    }
  }
}

Program.cs
在我的 IDE 中看起来像,

// Program.cs
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

当我使用终端运行代码时

dotnet run
它在我的计算机上完美运行。

当我创建一个新的cs文件时,它包含

// hello.cs
Console.WriteLine("hello world");

运行后显示

Only one compilation unit can have top-level statements. 

当我使用类方法和命名空间时

// hello.cs
namespace helloworld
{
    class hello
    {
        static void Main()
        {
            Console.WriteLine("hello world");

        }
    }
}

它运行

Program.cs
文件而不是新文件并显示此警告

PS C:\Users\User\C#projects> dotnet run hello.cs C:\Users\User\C#projects\hello.cs(5,21): warning CS7022: The entry point of the program is global code; ignoring 'hello.Main()' entry point. [C:\Users\User\C#projects\C#projects.csproj]   Hello, World!

项目结构:

我尝试了另一种方法,按

run and debug
,但什么也没显示。

当我单击 Generate c# Assets for Build and Debug 按钮时,它会显示此

无法找到 .NET Core 项目。资产未生成。

c# .net visual-studio-code entry-point toplevel-statement
3个回答
11
投票

C# 9 功能:顶级语句

这是 C# 9 中新引入的功能,称为 顶级语句

您引用的视频可能使用较低版本的 C#(低于 C# 9)。我们用来获取的地方

namespace helloworld
{
    class hello
    {
        static void Main()
        {
            Console.WriteLine("hello world");  
        }
    }
}

作为主程序的默认结构。

如果仔细观察,您会发现只有一行代码将字符串打印到控制台,即

Console.WriteLine("hello world");  

引入顶级语句是为了从此控制台应用程序中删除不必要的仪式

当您使用 C#9 或更高版本时,

dot net run
使用顶级语句成功编译代码,但是当您将单行代码替换为遗留结构时,编译器会警告您有关 Main 函数和 Main 的全局条目您通过替换顶级语句添加的 () 函数。

为了获得更清晰的信息,您可以浏览 MSDN 文档: 高层声明


为什么会收到错误“只有一个编译单元可以有顶级语句。”?

  • 根据 MSDN 文档,应用程序必须只有一个入口点。
  • 一个项目可以有只有一个包含顶级语句的文件。
  • 创建新文件时,添加了一个新的顶级语句,这会导致以下编译时错误:

CS8802 只有一个编译单元可以有顶级语句。


如何解决?

  • 根据上述解释,您的项目不应包含两个或多个顶级语句。要修复此错误,您可以删除稍后添加的文件。

0
投票

Microsoft Documentation

查看文档,它清楚地表明您不能在多个源文件中包含顶级语句。 也许您之前创建了一个 Program.cs 文件,将其删除并创建了另一个文件。先前的文件将由 VS Code 缓存。关闭 VS Code 并再次打开。如果这不起作用,请检查其他 .cs 文件。


0
投票

请检查您的项目文件夹内是否没有任何其他具有相同程序的工作项目。cs

© www.soinside.com 2019 - 2024. All rights reserved.