是的,這是一段很小的代碼,但我仍然懷疑是否有內置替換。是否存在與C#的'checked'關鍵字等效的Java?
下面的代碼:
/**
* Cast x to int, throw an exception if there's loss of information
*/
public static int safeLongToInt(long x)
{
int result = (int) x;
if (result != x)
throw new RuntimeException("long doesn't fit in an int: " + x);
return result;
}
在C#中的代碼是:
int foo;
long bar = ...;
checked
{
foo = bar;
}
1,因爲我從來沒有真正需要之前的「檢查」關鍵字。這裏是其他人感興趣的MSDN ref incase:http://msdn.microsoft.com/en-us/library/74b4xzyw(VS.71).aspx – CodingWithSpike 2009-11-03 18:45:55
哇,在C#中實際上有一個*關鍵字*?這真的是你經常這樣做的一個關鍵詞是爲了什麼? – 2009-11-04 00:41:44
更有趣的是,有'checked'和'unchecked'兩個關鍵字,如果兩個都沒有使用,默認情況是由編譯選項設置的。 – 2009-11-04 00:47:22