简体   繁体   English

C#程序中return语句的目的是什么

[英]What is the purpose of return statement in C# programs

What is the purpose of a return statement. 退货声明的目的是什么?

Example : 示例

Class Sample 
{
    public static int Main()
    {
      System.Console.WriteLine("Hello World");
      return 0;
    } 
}

In the above program what actually is being returned. 在上面的程序中实际返回的是什么。 Is it returning integer value 0 ? 它返回整数值0吗? Does this help in the flow of program execution 这对程序执行流程有帮助吗?

(This might be a stupid question, but I am eager to know.) (这可能是一个愚蠢的问题,但我很想知道。)

The exit code of the application is set to the value returned from Main. 应用程序的退出代码设置为从Main返回的值。 This can be used to communicate to the calling application if there was an error or everything succeeded when running the child application. 如果在运行子应用程序时出现错误或一切都成功,则可以使用此方法与调用应用程序进行通信。

When running from the console window, the last exit code is set in the environment variable which can be used to control the execution of a batch file for example. 从控制台窗口运行时,最后一个退出代码在环境变量中设置,该变量可用于控制批处理文件的执行。

See the following MSDN entry for more info and an example. 有关详细信息和示例,请参阅以下MSDN条目。 http://msdn.microsoft.com/en-us/library/0fwzzxz2.aspx http://msdn.microsoft.com/en-us/library/0fwzzxz2.aspx

The exit code of an application (return from main) can be queried in the operating system or in batch programs. 可以在操作系统或批处理程序中查询应用程序的退出代码(从main返回)。 In windows, it can be processed in a batch using the %errorlevel% environment var. 在Windows中,可以使用%errorlevel%environment var批量处理它。

@echo off
yourpgrogram
echo Your program returned %errorlevel%

would brint out Your program returned 0 你的程序会返回0

hth 心连心

Mario 马里奥

From the Main() method, the value returned will affect the program's exit code . Main()方法,返回的值将影响程序的退出代码 From MSDN : 来自MSDN

... returning an integer enables the program to communicate status information to other programs or scripts that invoke the executable file. ...返回一个整数使程序能够将状态信息传递给调用可执行文件的其他程序或脚本。

return 0是执行中没有错误的约定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM