C# 数组使用未分配的局部变量
C# arrays use of unassigned local variable
在这段代码中,我试图将 0 到 9 之间的随机数添加到一个数组中,但是当我试图在 for 循环内将数字分配给数组时,我收到此错误:
Error 1 Use of unassigned local variable 'x'
代码如下:
using System;
class Core
{
public static void Main()
{
Random rnd = new Random();
int[] x;
for (int i = 0; i < 4; i++)
{
x[i] = rnd.Next(1, 9);
}
}
}
我已经阅读了 Compiler Error CS0165 的 MSDN 描述,但它没有讨论数组。
您需要初始化数组并为其分配大小。
int[] x = new int[4];
在这段代码中,我试图将 0 到 9 之间的随机数添加到一个数组中,但是当我试图在 for 循环内将数字分配给数组时,我收到此错误:
Error 1 Use of unassigned local variable 'x'
代码如下:
using System;
class Core
{
public static void Main()
{
Random rnd = new Random();
int[] x;
for (int i = 0; i < 4; i++)
{
x[i] = rnd.Next(1, 9);
}
}
}
我已经阅读了 Compiler Error CS0165 的 MSDN 描述,但它没有讨论数组。
您需要初始化数组并为其分配大小。
int[] x = new int[4];