c#System.OverflowException

c# System.OverflowException

所以这是我的代码:

static void Main(string[] args)
{
    Console.WriteLine("How many numbers are you going to enter?");

    long num = long.Parse(Console.ReadLine());

    long[] nums = new long[num];
}

当我为 "num" 输入 10000000000 时,我得到

"System.OverflowException Arithmetic operation resulted in an overflow."

我该如何解决?

您的代码溢出,因为 C# 中数组的最大大小为 Int32.MaxValue,等于 2147483647。您可以在 source code, and it is clearly stated in the documentation:

中查看提示

By default, the maximum size of an Array is 2 gigabytes (GB). In a 64-bit environment, you can avoid the size restriction by setting the enabled attribute of the configuration element (<gcAllowVeryLargeObjects> introduced in .NET 4.5) to true in the run-time environment. However, the array will still be limited to a total of 4 billion elements, and to a maximum index of 0X7FEFFFFF (2146435071) in any given dimension (0X7FFFFFC7 (2147483591) for byte arrays and arrays of single-byte structures).

好的,您正在尝试分配大量 内存,因为调用长数组构造函数实际上已经释放了您请求的内存。 A long 是 64 位,所以是 8 个字节。 8 字节 * 10000000000 = 80 GB 内存。太过分了

假设您有足够的内存,C# 中数组的最大长度为 int.MaxValue,即 2,147,483,647(使用 long 时为 16GB)。