Array.Sum()导致溢出

vdt*_*the 4 c# arrays int sum overflow

我有一个像这样的int数组

int[] arr = {256741038,623958417,467905213,714532089,938071625};
Run Code Online (Sandbox Code Playgroud)

然后我创建了一个int64 var

Int64 sum = arr.Sum();
Run Code Online (Sandbox Code Playgroud)

但这在溢出中重新出现

运行时异常(第19行):算术运算导致溢出.

如何在不使用循环来总结的情况下解决这个问题?(数组类型必须为int)

Joh*_*ica 9

您需要将值long强制转换为(或者将数字设置为大的数据类型,但是因为您正在使用Int64 ...):

long sum = arr.Sum(v => (long)v);
Run Code Online (Sandbox Code Playgroud)