8
誰能詳細聲明如下意義:什麼是使用檢查這裏
byte[] buffer = new Byte[checked((uint)Math.Min(32 * 1024, (int)objFileStream.Length))];
,爲什麼我不應該使用
byte[] buffer = new Byte[32 * 1024];
誰能詳細聲明如下意義:什麼是使用檢查這裏
byte[] buffer = new Byte[checked((uint)Math.Min(32 * 1024, (int)objFileStream.Length))];
,爲什麼我不應該使用
byte[] buffer = new Byte[32 * 1024];
試圖拋出異常,如果objFileStream.Length
將返回更大的號碼,然後int.MaxValue
(因爲Length
在Stream
返回long
類型(我假設objFileStream
是流)。在.net默認情況下不檢查算術溢出。
接下來的代碼演示了這種情況:
long streamLength = long.MaxValue; //suppose buffer length is big
var res = checked((int)(streamLength + 1)); //exception will be thrown
Console.WriteLine(res); //will print 0 in you comment checked keyword
簡短分析後,可以降低未來的語句
new Byte[checked((uint)Math.Min(32 * 1024, (int)objFileStream.Length))];
到
new Byte[Math.Min(32 * 1024, checked((int)objFileStream.Length))];
個人推薦:我怎麼沒看到OverflowException
會幫助你在這裏。 Math.Min
將會保留,該陣列將不會超過32768
項目。如果您嘗試在調用方法的某個位置嘗試catch
,則無法推斷出錯的原因是什麼,它可能來自調用堆棧中的任何位置。
所以你可能不需要總是分配大小32768的數組,你提出
byte[] buffer = new Byte[32 * 1024];
,但仍使用Math.Min
,讓你節省存儲,如果objFileStream.Length
將返回少數
byte[] buffer = new Byte[Math.Min(32 * 1024, objFileStream.Length)];