Main方法是C#控制台應用程序和Windows窗體應用程序的入口點。Main方法可以有形參,也可以沒有,可以有返回值(int整型),也可以沒有。如下定義:
無返回值、無形參的格式: static void Main(){ //to do sth } 無返回值、有形參的格式: static void Main(string[] args){ //to do sth } 有返回值、無形參的格式: static int Main(){ //to do sth return 0; } 有返回值、有形參的格式: static int Main(string[] args){ //to do sth return 0; }
Main方法必須為靜態形式,訪問修飾符不能為public。因C#類中默認的訪問修飾符為private,因此可以不寫。
在外部可以通過輸入命令行參數的形式啟動應用程序,從而進入程序的入口(Main方法)。
在開始菜單中打開“Visual Studio開發人員命令提示”窗口,然后導航到cs文件所在目錄。用csc命令編譯包含Main方法的cs文件,如:csc test.cs。如果編譯成功,當下目錄會生成一個test.exe應用程序,這時可用test param1 param2命令調用應用程序並執行應用程序,每個參數之間用空格隔開,如果參數中有空格,就用雙引號將該參數圍着,這樣應用程序就會將它識別為一個參數,而不是多個。
命令行輸入格式如下:
命令行輸入格式 | 傳遞給Main方法的字符串數組格式 |
test one two three | "one" "two" "three" |
test a b c | "a" "b" "c" |
test "one two" three | "one two" "three" |
測試代碼如下:
class test{ static int Main(string[] args){ int count=1; if(args!=null && args.Length>0) foreach(string item in args) System.Console.WriteLine("第{0}個參數:{1}",count++,item); else System.Console.WriteLine("沒有輸入任何參數!"); System.Console.WriteLine("程序結束!"); return 0; } }
測試結果如圖:
可以用批處理文件來運行C#應用程序,並根據應用程序返回的整型結果進行下一步邏輯操作。
在Windows中執行程序時,Main方法返回的任何值都將保存到名為ERRORLEVEL的環境變量中。可以通過檢查ERRORLEVEL變量的值,批處理文件可以確定程序執行的結果。通常可以將返回值設置為0,用來表示程序執行成功的標志。
test.bat批處理文件內容如下:
rem test.bat @echo off test one two three @if "%ERRORLEVEL%" == "0" goto Success :Failed echo program execute failed echo the return value is %ERRORLEVEL% goto End :Success echo program execute success echo the return value is %ERRORLEVEL% goto End :End pause
批處理test.bat執行結果如下: