unchecked (C# 參考)
unchecked 關鍵字是用來隱藏整數類資料型別 (Integral Type) 之算術運算和轉換的溢位檢查。
在不檢查 (Unchecked) 的內容中,如果運算式產生在目的型別範圍之外的值,不會以旗標標示溢位。 例如,因為下列範例中的計算會以 unchecked 區塊或運算式執行,所以,會忽略該結果對於整數而言太大的結果,同時,int1 會指派為值 -2,147,483,639。
unchecked
{
int1 = 2147483647 + 10;
}
int1 = unchecked(ConstantMax + 10);
如果移除環境 unchecked,則會發生編譯錯誤。 在編譯期間,因為運算式的所有條件都是固定的,所以可以偵測溢位。
根據預設,在編譯期間與執行階段,不會檢查包含非常數條件的運算式。 如需啟用檢查 (Checked) 環境的詳細資訊,請參閱 checked (C# 參考)。
因為檢查溢位耗費時間,所以在沒有溢位危險的情況中使用不檢查的程式碼,可以提升效能。 不過,如果仍有溢位的可能性,則必須使用檢查環境。
範例
這個範例顯示如何使用 unchecked 關鍵字。
class UncheckedDemo
{
static void Main(string[] args)
{
// int.MaxValue is 2,147,483,647.
const int ConstantMax = int.MaxValue;
int int1;
int int2;
int variableMax = 2147483647;
// The following statements are checked by default at compile time. They do not
// compile.
//int1 = 2147483647 + 10;
//int1 = ConstantMax + 10;
// To enable the assignments to int1 to compile and run, place them inside
// an unchecked block or expression. The following statements compile and
// run.
unchecked
{
int1 = 2147483647 + 10;
}
int1 = unchecked(ConstantMax + 10);
// The sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
Console.WriteLine(int1);
// The following statement is unchecked by default at compile time and run
// time because the expression contains the variable variableMax. It causes
// overflow but the overflow is not detected. The statement compiles and runs.
int2 = variableMax + 10;
// Again, the sum of 2,147,483,647 and 10 is displayed as -2,147,483,639.
Console.WriteLine(int2);
// To catch the overflow in the assignment to int2 at run time, put the
// declaration in a checked block or expression. The following
// statements compile but raise an overflow exception at run time.
checked
{
//int2 = variableMax + 10;
}
//int2 = checked(variableMax + 10);
// Unchecked sections frequently are used to break out of a checked
// environment in order to improve performance in a portion of code
// that is not expected to raise overflow exceptions.
checked
{
// Code that might cause overflow should be executed in a checked
// environment.
unchecked
{
// This section is appropriate for code that you are confident
// will not result in overflow, and for which performance is
// a priority.
}
// Additional checked code here.
}
}
}
C# 語言規格
如需詳細資訊,請參閱<C# 語言規格>。語言規格是 C# 語法及用法的限定來源。