任何人都可以详细说明以下声明:
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];
但如果 objFileStream.Length
将返回较小的数字,仍然使用 Math.Min
以节省存储空间
byte[] buffer = new Byte[Math.Min(32 * 1024, objFileStream.Length)];
关于c# - 这里用checked有什么意义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15807859/