简介
Main方法的返回值是程序的退出码(exit code),主要是用来告诉系统:程序是否正常执行完毕。
在linux系,exit code的标准定义是:
-
0- success
-
1- general errors
-
126- permission issue
-
127-Illegal command
-
128-Invalid arguments and fatal errors
-
255-Out of range
返回值是void类型
static void Main()
{
//...
}
返回值是int类型
static int Main()
{
//...
return 0;
}
linux/mac查看返回值
运行程序:
dotnet run
运行完上面之后,立马运行下面命令:
echo $?
-
$? 保存的是最近一次程序运行的exit code
-
注意:In Unix (Posix), the exit code is an 8-bit value: 0-255.
Windows获取返回值
-
运行在windows中的程序,main()方法返回的状态码会存储在环境变量ERRORLEVEL中;
-
示例Program.cs:
using System;
namespace _0004MainReturnValue
{
class Program
{
static int Main(string[] args)
{
Console.WriteLine("Hello World!");
return 0;
}
}
}
使用csc编译Program.cs 生成Program.exe可执行文件
csc.exe Program.cs
创建一个批处理文件test.bat来执行Program.exe,并获取其返回值。
@echo off Program.exe @if "%ERRORLEVEL%" == "0" goto success :failed echo Execution Failed echo return value = %ERRORLEVEL% goto end :success echo Execution succeeded echo Return value = %ERRORLEVEL% goto end :end