如何修复顶层语句的错误?(该问题涉及IT技术)

3

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();

在模块控制台下,它弹出一个错误: 只有一个编译单元可以拥有顶级语句。 错误:CS8802
我在终端中尝试了dotnet new console --force,但它最终只是删除了我的程序。 我想在同一个文件夹中运行多个C#文件,而不会出现只有一个编译单元可以拥有顶级语句或其他类似的错误。

1
你想同时运行多个程序吗?它们都需要读取控制台输入。那会怎样运行呢? - Charles Mager
1
错误信息难道不很明显吗?您只需获取一个文件,就可以避免定义类的麻烦。 - Kirk Woll
这是指我需要为我的C#文件创建一个新文件夹吗? - Canyon
@Canyon,一个文件夹不会有任何区别。你实际上想要做什么?你可以在另一个文件中定义其他内容(例如类),但你上面实际上正在定义两个“Main”方法/入口点。你只能有一个这样的方法,执行多个没有意义。 - Charles Mager
1个回答

5
在dotnet 6中,您不需要为主方法指定类名。
因此,当您有两个没有类和命名空间的类时,编译器会认为您有两个主方法。
所以你可以这样做:
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();
    }
}

否则,这就像说有2个public static void Main(string[] args)方法一样,而这是不可能的。

我如何选择要运行的程序? - Canyon
1
包含Main方法的程序,因此Main是您程序的入口点。程序只是一个类。 - Maytham Fahmi
1
我会更改我的答案,以便给您更好的了解。 - Maytham Fahmi
1
现在,program1包含一个带有一些逻辑的方法,而program2调用program1中的一个方法。Program2具有Main方法,该方法是启动程序的入口点。 - Maytham Fahmi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接