我意识到这是 7 岁,但我只是遇到了这个。我认为实际上调用可执行文件并关闭当前程序有点麻烦。如前所述,这是多虑了。我认为最干净和最模块化的方法是采用 Main 方法中的所有内容并制作一个不同的方法,假设 Run() 包含 Main 方法中的所有内容,然后调用新的 @987654324 @ 方法来自Main 方法或代码中需要重新启动程序的任何位置。
如果Main 方法看起来像这样:
static void Main(string[] args)
{
/*
Main Method Variable declarations;
Main Method Method calls;
Whatever else in the Main Method;
*/
int SomeNumber = 0;
string SomeString = default(string);
SomeMethodCall();
//etc.
}
然后只需创建一个Run() 方法并将Main 中的所有内容放入其中,如下所示:
public static void Run()
{
//Everything that was in the Main method previously
/*
Main Method Variable declarations;
Main Method Method calls;
Whatever else in the Main Method;
*/
int SomeNumber = 0;
string SomeString = default(string);
SomeMethodCall();
//etc.
}
现在 Run() 方法已创建,它包含之前 Main 方法中的所有内容,只需将您的 main 方法设为:
static void Main(string[] args)
{
Run();
}
现在,无论您想在代码中的何处“重新启动”程序,只需像这样调用Run() 方法:
if(/*whatever condition is met*/)
{
//do something first
//then "re-start" the program by calling Run();
Run();
}
所以这是对整个程序的简化:
编辑:当我最初发布此内容时,我没有考虑任何可能已传递给程序的参数。为了解释这四件事,我的原始答案需要改变。
-
像这样声明一个全局List<string>:
public static List<string> MainMethodArgs = new List<string>();。
-
在Main 方法中,将MainMethodArgs 列表的值设置为等于
通过args 传递给Main 方法的值如下:
MainMethodArgs = args.ToList();
-
创建Run() 方法时,更改签名,使其期望
string[] 调用 args 以像这样传递给它:
public static void Run(string[] args)
{
....
}
-
在程序中调用Run()方法的任何地方,传递MainMethodArgs
像这样给Run():
Run(MainMethodArgs.ToArray());
我更改了下面的示例以反映这些更改。
using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExampleConsole
{
class Program
{
public static List<string> MainMethodArgs = new List<string>();
static void Main(string[] args)
{
MainMethodArgs = args.ToList();
Run(MainMethodArgs.ToArray());
}
public static void Run(string[] args)
{
Console.WriteLine("Run() is starting");
Console.ReadLine();
//stuff that used to be in the public method
int MainMethodSomeNumber = 0;
string MainMethodSomeString = default(string);
SomeMethod();
//etc.
}
public static void SomeMethod()
{
Console.WriteLine("Rebuild Log Files"
+ " Press Enter to finish, or R to restar the program...");
string restar = Console.ReadLine();
if (restar.ToUpper() == "R")
{
//here the code to restart the console...
Run(MainMethodArgs.ToArray());
}
}
}
}
实际上,程序被“重新启动”,而无需重新运行可执行文件并关闭程序的现有实例。这对我来说似乎更像“程序员”。
享受吧。