任何人都可以详细说明以下声明:
byte[] buffer = new Byte[checked((uint)Math.Min(32 * 1024, (int)objFileStream.Length))];
为什么我不应该使用
byte[] buffer = new Byte[32 * 1024];
objFileStream.Length
如果返回的数字大于int.MaxValue
(2147483647),则尝试抛出异常,因为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)];