28 9月 2011

[C#] 用 checked 來避免溢位

當進行強制轉換時,容易因為長短不同而造成溢位(overflow)

// Bad 
short shortNum;
int i = 32768;
shortNum = (short) i; 
// problem after statment excution
// the shortNum variable has an uninitialized value,


// Good
try {
  shortNum = checked((short)i); // solution 
}
catch(OverflowException efx) {}

沒有留言:

張貼留言