小编Mou*_*ari的帖子

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

我刚刚开始学习 C#,我创建了 C# 控制台应用程序。为了理解这些概念,我观看了如何为 C# 设置与代码的视频

dotnet new console当我在 VS code 终端中运行命令时,它会创建一个包含Program.cs文件的新项目。

在视频中,该Program.cs文件看起来像这样

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

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

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

当我使用终端运行代码时,dotnet run它在我的计算机上完美运行。

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

// hello.cs
Console.WriteLine("hello world");
Run Code Online (Sandbox Code Playgroud)

运行后它说 Only one compilation unit can have top-level statements.

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

// hello.cs
namespace helloworld
{
    class …
Run Code Online (Sandbox Code Playgroud)

.net c# entry-point visual-studio-code toplevel-statement

10
推荐指数
1
解决办法
2万
查看次数