C#数组使用未赋值的局部变量 [英] C# arrays use of unassigned local variable
本文介绍了C#数组使用未赋值的局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这段代码中,我尝试将 0 到 9 之间的随机数添加到数组中,但是当我尝试在 for 循环内为数组分配数字时,我收到此错误:
Here in this piece of code I'm trying to add random numbers between 0 to 9, to an array but when I'm trying to assign numbers to the array inside a for loop, I receive this error:
错误 1 使用未赋值的局部变量 'x'
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);
}
}
}
我已经阅读了关于 编译器错误 CS0165 的 MSDN 描述,但是它不谈论数组.
I've read MSDN description for the Compiler Error CS0165 but it does not talk about arrays.
推荐答案
您需要初始化数组并为其分配大小.
You need to initialise and assign a size to your array.
int[] x = new int[4];
这篇关于C#数组使用未赋值的局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文