什么是使用检查这里

什么是使用检查这里

问题描述:

谁能详细声明如下意义:什么是使用检查这里

byte[] buffer = new Byte[checked((uint)Math.Min(32 * 1024, (int)objFileStream.Length))]; 

,为什么我不应该使用

byte[] buffer = new Byte[32 * 1024]; 

试图抛出异常,如果objFileStream.Length将返回更大的号码,然后int.MaxValue(因为LengthStream返回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)];