8

任何人都可以详细说明以下声明:

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

为什么我不应该使用

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

1 回答 1

5

objFileStream.Length如果返回的数字大于int.MaxValue(2147483647),则尝试抛出异常,因为Length返回类型Streamlong我假设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)]; 
于 2013-04-04T09:52:20.760 回答