簡體   English   中英

如何修復頂級語句的錯誤?

[英]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();

程序2.cs

Console.ReadKey();

在模塊Console下報錯: Only one compilation unit can have top-level statements。 錯誤:CS8802

我在終端do.net new console --force中嘗試過,但它最終刪除了我的程序。 我想在同一文件夾中運行多個 C# 文件而不會出現Only one compilation unit can have top-level statements或其他類似錯誤。

在 do.net 6 中,main 方法不需要 class 名稱。

因此,當您有 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.");
    }
}

對於 program2,有些人認為:

namespace ConsoleApp1;

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

否則,就像說有 2x public static void Main(string[] args)而這是不可能的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM