首先,我要说的是我不是C#的初学者,但也不太精通,需要帮助将值返回给主函数。或者更确切地说,告诉我什么是“正确”的方式。
如果出现任何异常并进入catch块,则我想在应用程序中返回失败值(简单地为-1)。在这种情况下,将信息传递给主函数以返回-1。
我解决这个问题的方法是添加一个静态全局变量mainReturnValue(以便从主函数中访问它),并在catch块中将其值设置为-1。
基于我的当前代码,这样做是正确的吗?
如果有人想知道,该应用程序是在没有用户交互的情况下执行的,这就是为什么我需要捕获退出状态的原因。表单/ GUI只显示有关进度的信息,以防它被手动启动。
namespace ApplicationName
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{ ...
static int mainReturnValue = 0; //the return var
static int Main(string[] args)
{
Application.Run(new Form1(args));
return mainReturnValue; //returning 0 or -1 before exit
}
private void Form1_Load(object sender, System.EventArgs e)
{
the code..in turn also calling some sub functions such as DoExportData...and I want to be able to return the value to main from any function...
}
private int DoExportData(DataRow dr, string cmdText)
{
try { ... }
catch
{ mainReturnValue = -1; }
}
感谢您的选择。
Application.Run()
执行完毕后,窗体将不再显示,但由form1
引用的对象仍然存在。 - Galax