我是一名新手,正在学习C#并且现在致力于控制台应用程序。以下是我写的代码:
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ch06Ex01
{
class Program
{
static void Write()
{
Console.WriteLine("Please enter any string..!!");
}
static void Main(string[] args)
{
Write();
string name = Console.ReadLine();
Write();
string name1 = Console.ReadLine();
Write();
string name2 = Console.ReadLine();
Write();
string name3 = Console.ReadLine();
Console.WriteLine("{0}, {1}, {2}, {3}",name,name1,name2,name3);
Console.WriteLine("enter \"y\" to restart the program and \"n\" to exit the Program");
string selectedOption = Console.ReadLine();
if (selectedOption == "y")
{
// howto call static void Main(string[] args) here agin so that the program start itself from the start point
}
//else if (selectedOption == "n")
{
//Terminate the Program
}
Console.ReadKey();
}
}
现在到了这个点:
if (selectedOption == "y")
{
// howto call static void Main(string[] args) here agin so that the program start itself from the start point
}
我希望如果用户输入“y”,程序能够重新启动,如果用户输入“n”,程序能够终止。为了实现这个目的,我首先尝试使用goto语句,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ch06Ex01
{
class Program
{
static void Write()
{
Console.WriteLine("Please enter any string..!!");
}
static void Main(string[] args)
{
StartPoint;
Write();
string name = Console.ReadLine();
Write();
string name1 = Console.ReadLine();
Write();
string name2 = Console.ReadLine();
Write();
string name3 = Console.ReadLine();
Console.WriteLine("{0}, {1}, {2}, {3}",name,name1,name2,name3);
Console.WriteLine("enter \"y\" to restart the program and \"n\" to exit the Program");
string selectedOption = Console.ReadLine();
if (selectedOption == "y")
{
// howto call static void Main(string[] args) here agin so that the program start itself from the start point
goto StartPoint;
}
//else if (selectedOption == "n")
Console.ReadKey();
}
}
}
但是在
StartPoint;
处,它对我无效,会出现错误。Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement C:\Users\Ahsan\Desktop\C# for Beginners Examples\Ch06Ex01\Ch06Ex01\Program.cs 18 13 Ch06Ex01
然后我尝试在该点调用主函数本身。
if (selectedOption == "y")
{
// howto call static void Main(string[] args) here agin so that the program start itself from the start point
}
但是这里给了我很多错误,现在不知道该怎么办,请问有谁能帮帮我吗?我不知道如何让这个东西工作起来... 更好的方法可能是在类中再次调用 " static void Main(string[] args) "。
while(Console.ReadKey()!='<some exit char>') {code here}
。 - kravasbMain
的完整代码块,否则您的应用程序将不会结束。 在这种情况下,第一个对Main
的调用将在内部main
完成之前无法解决。 如果您不断递归,可能会冒堆栈溢出的风险。 但是,由于Main
具有void
返回类型,可能会发生一些尾调用优化。 使用“while”循环是解决此问题的典型C#方法。 - Adam Kewley