如何修复顶级语句的错误?

How do I fix the top-level statement's error?

Program1.cs 常规 C# 文件,完美运行。

Random numberGen = new Random();

int roll1 = 1;
int roll2 = 0;
int roll3 = 0;
int roll4 = 0;

int attempts = 0;

Console.WriteLine("Press enter to roll the dies");

while (roll1 != roll2 || roll2 != roll3 || roll3 != roll4 || roll4 != roll1)
{
    Console.ReadKey();

    roll1 = numberGen.Next(1, 7);
    roll2 = numberGen.Next(1, 7);
    roll3 = numberGen.Next(1, 7);
    roll4 = numberGen.Next(1, 7);
    Console.WriteLine("Dice 1: " + roll1 + "\nDice 2: " + roll2 + "\nDice 3: " + roll3 + "\nDice 4: " + roll4 + "\n");
    attempts++;
}

Console.WriteLine("It took " + attempts + " attempts to roll a four of a kind.");

Console.ReadKey();

Program2.cs

Console.ReadKey();

在模块Console下弹出错误: 只有一个编译单元可以有顶层语句。错误:CS8802

我在终端 dotnet new console --force 中尝试过,但它最终删除了我的程序。 我想 运行 同一文件夹中的多个 C# 文件而不获取 只有一个编译单元可以有顶级语句或其他类似错误。

在 dotnet 6 中,您不需要 class main 方法的名称。

所以当你有 2 个没有 class 和命名空间的 class 时,编译器认为你有 2 个主要方法。

所以你做类似的事情

namespace ConsoleApp1;

class Program1
{
    public static void GetRolling()
    {
        Random numberGen = new Random();

        int roll1 = 1;
        int roll2 = 0;
        int roll3 = 0;
        int roll4 = 0;

        int attempts = 0;

        Console.WriteLine("Press enter to roll the dies");

        while (roll1 != roll2 || roll2 != roll3 || roll3 != roll4 || roll4 != roll1)
        {
            Console.ReadKey();

            roll1 = numberGen.Next(1, 7);
            roll2 = numberGen.Next(1, 7);
            roll3 = numberGen.Next(1, 7);
            roll4 = numberGen.Next(1, 7);
            Console.WriteLine("Dice 1: " + roll1 + "\nDice 2: " + roll2 + "\nDice 3: " + roll3 + "\nDice 4: " + roll4 + "\n");
            attempts++;
        }

        Console.WriteLine("It took " + attempts + " attempts to roll a four of a kind.");
    }
}

对于程序 2,有些人认为:

namespace ConsoleApp1;

public class Program2
{
    public static void Main(string[] args)
    {
        Program1.GetRolling();
        Console.ReadKey();
    }
}

否则就等于说有2xpublic static void Main(string[] args)是不可能的