checked(已檢驗)——用于設置溢出檢驗上下文(overflow-checking context),控制對整型算術表達式中的操作和轉換進行溢出檢驗,在出現溢出時會拋出異常。格式為:checked(表達式)或checked{語句塊}。
unchecked(未檢驗)——用于設置溢出檢驗上下文(overflow-checking context),控制對整型算術表達式中的操作和轉換不進行溢出檢驗,在出現溢出時不拋出異常,結果為截斷后的整數。格式為:unchecked(表達式)或unchecked{語句塊}。
例如:
class Test {
static readonly int x = 1000000;
static readonly int y = 1000000;
static int F() {
return checked(x * y); // Throws OverflowException
}
static int G() {
return unchecked(x * y); // Returns -727379968
}
static int H() {
return x * y; // Depends on default
}
}
又例如:
try {
int i, i2 = int.MaxValue, i2 = 200;
i = checked(i1 * i2);
} catch(Exception e){
//MessageBox.Show(e.ToString());
Console.WriteLine(e.ToString());
}
新聞熱點
疑難解答