我刚刚开始学习 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# 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 文档: 高层声明
为什么会收到错误“只有一个编译单元可以有顶级语句。”?
CS8802 只有一个编译单元可以有顶级语句。
如何解决?
请检查您的项目文件夹内是否没有任何其他具有相同程序的工作项目。cs