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();
在模块控制台下,它会弹出一个错误:只有一个编译单元可以具有顶级语句错误:CS8802
我在终端dotnet新控制台--force中尝试过,但它最终删除了我的程序。我想在同一文件夹中运行多个C#文件,而不获取只有一个编译单元可以有顶级语句或其他类似错误。
在dotnet6中,主方法不需要类名。
因此,当您有两个没有类和名称空间的类时,编译器认为您有两种主要方法。
所以你做了一些类似的事情
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)
,这是不可能的。