環境類提供有關當前平台的信息並操作當前平台。 Environment 類可用於獲取和設置各種操作 system-related 信息。我們可以使用它來檢索 命令行 參數信息、退出代碼信息、環境變量設置信息、調用堆棧信息的內容以及自上次係統啟動以來的時間(以毫秒為單位)信息。通過使用一些預定義的方法,我們可以使用 Environment 類獲取操作係統的信息,Exit() 方法就是其中之一。它用於終止程序的當前進程並將退出代碼返回給操作係統。調用 Exit() 方法與 return 語句的工作方式有以下不同:
- 此方法始終終止應用程序,而 return 語句可能僅在入口點中使用時終止應用程序。就像在 main 方法中一樣。
- 即使其他線程正在運行,此方法也會立即終止代碼。而 return 語句在應用程序的入口點調用,並且僅在所有前台線程終止時才終止應用程序。
- 此方法要求調用者有權調用非托管代碼。而 return 語句沒有。
- 當從 try 或 catch 塊調用此方法時,任何 finally 塊中的代碼都不會執行。雖然使用從 try 或 catch 塊調用的 return 語句,但 finally 塊中的代碼會執行。
- 如果在受約束的執行區域 (CER) 中的代碼正在運行時調用 Exit 方法,則 CER 將不會完全執行。而使用 return 語句則 CER 完全執行。
用法:
Environment.Exit(int exitCode);
其中 exitCode 是整數類型的參數。它表示將返回操作係統的退出代碼。當此參數的值為零時,則表示該過程已完成。當此參數的值非零時,則表示該過程未成功完成,或者我們可以說零值表示錯誤。
異常:當檢測到安全錯誤時,它隻會拋出 SecurityException。
範例1:
C#
// C# program to illustrate Exit() method
// of Environment class
using System;
class GFG{
static public void Main()
{
Console.WriteLine("Code before Exit() function");
// Exit the program
// Using Exit() method
Environment.Exit(0);
Console.WriteLine("Code after Exit() function");
}
}
輸出:
Code before Exit() function
範例2:
C#
// C# program to illustrate Exit() method
// of Environment class
using System;
class GFG{
static public void Main()
{
Console.WriteLine("Code Before Exit() function will work");
// Perform addition
int add = 9 + 11;
Console.WriteLine("Sum:" + add);
// Perform subtraction
int subtr = 9 - 11;
Console.WriteLine("Subtract:" + subtr);
// Exit the program
Environment.Exit(0);
Console.WriteLine("Code Before Exit() function will not work");
// Perform multiplication
int mult = 9 * 11;
Console.WriteLine("Multiplication:" + mult);
// Perform division
int divide = 10/5;
Console.WriteLine("Divide:" + divide);
}
}
輸出:
Code Before Exit() function will work Sum:20 Subtract:-2
相關用法
注:本文由純淨天空篩選整理自manojkumarreddymallidi大神的英文原創作品 C# Program to Demonstrate the Use of Exit() Method of Environment Class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。