2011-07-10 75 views
3

我會開始說,我不是C#的初學者,但不是非常多,需要幫助返回值爲主。或者告訴我什麼是「正確」的方式。返回值到主C#

我想從應用程序中返回一個失敗值(僅爲-1),以防發生任何異常並以catch結尾。在這種情況下,將信息傳遞給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; } 
} 

謝謝。

回答

7

你可以這樣做:

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

我不明白這是如何工作的。你只通過關閉'form1'來到'Application.Run'後面的行。那時'form1.Result'不再存在 –

+0

@EMett'Application.Run()'完成後,表單將不再顯示,但'form1'引用的對象仍然存在。 – Galax

1

我想補充像這樣

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


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

只是可以肯定,即使未處理的異常在你想要的方式「處理」的應用程序,因爲我假定你的應用不僅是一個WindowsForm。