c# - 将值返回到主 C#

标签 c#

首先我会说我不是 C# 的初学者,但也不是很多,需要帮助将值返回给 main。或者更确切地说,告诉我什么是“正确”的方式。

我想从应用程序返回一个失败值(简单的 -1),以防出现任何异常并以捕获结束。在这种情况下,将信息传递给 main 以返回 -1。

我解决它的方法是添加一个静态全局变量 mainReturnValue(以便能够从 main 访问它),并在捕获中将其值设置为 -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; }
}  

谢谢。

最佳答案

你可以这样做:

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; 
    }
}

关于c# - 将值返回到主 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6643598/

相关文章:

javascript - 使用knockout js上传文件

c# - 将元素插入列表时索引超出范围异常

c# - 澄清 IL 生成的引用字符串的代码

c# - System.Drawing 的撤消按钮?

c# - EPPlus 自定义标题列名称

c# - 为什么 var 在 XmlNodeList 循环中推断类型对象而不是 XmlNode?

c# - 在 jquery ajax 中处理 json 响应

c# - 使用 ngen.exe 创建和分发 native 镜像

c# - 在 C# 中以异步方式发送 5000 条消息

c# - 我应该如何在 DocumentDb 中存储大量行