我刚开始学习c#,我创建了C#控制台应用程序。为了理解这些概念,我观看了如何为c#设置vs代码的视频。
当我在VS代码终端中运行dotnet new console
命令时,它会创建一个包含Program.cs
文件的新项目。
在视频中,Program.cs
文件显示为
// Program.cs
using System;
namespace HelloWorld
{
class Program
{
static string Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
在我的IDE中出现了Program.cs
,
// 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#按钮时,它会显示如下
无法定位.NET核心项目。没有产生资产。
发布于 2022-06-07 10:44:04
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只有一个编译单元可以有顶级语句.
如何修复它?
https://stackoverflow.com/questions/72529648
复制相似问题