首先我会说我不是 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/