将值返回到主函数C#

3

首先,我要说的是我不是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; }
}  

感谢您的选择。
3个回答

8
你可以这样做:
static int Main(string[] args)
{
    Form1 form1 = new Form1(args);
    Application.Run(form1);
    return form1.Result;
}

然后在Form1类上定义一个属性,在DoExportData方法执行后可以设置该属性的值。例如:

public int Result { get; private set; }

private void Form1_Load(object sender, System.EventArgs e)
{ 
    Result = DoExportData(...);
}

private int DoExportData(DataRow dr, string cmdText)
{
    try 
    {
        ...
        return 0;
    } 
    catch
    { 
        return -1; 
    }
}

我不明白这个怎么能够运行。只有在关闭“form1”之后,才能到达“Application.Run”后面的代码行。但是在那时,“form1.Result”已经不存在了。 - E Mett
@EMett 在 Application.Run() 执行完毕后,窗体将不再显示,但由 form1 引用的对象仍然存在。 - Galax

2

1

我会加上类似这样的东西

  AppDomain currentDomain = AppDomain.CurrentDomain;
  currentDomain.UnhandledException += new UnhandledExceptionEventHandler(CrashHandler);


  static void CrashHandler(object sender, UnhandledExceptionEventArgs args) {
     mainReturnValue = -1;
  }

为确保即使未处理的异常也按您希望的方式由您的应用程序“处理”,因为我假设您的应用程序不仅仅是一个WindowsForm。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接