我查看了之前的问题,但没有帮助。 我有一个用 C# 编写的非常简单的函数。 它给我编译器错误“使用未分配的局部变量'linea'”(第(2)行)。 可能出什么问题了?请告诉我如何纠正它?
public void llenarTabla()
{
int idx;
string[] linea; (1)
for (idx = 0; idx < numListas; idx++)
{
linea[0] = Convert.ToString(idx); // (2)
switch(OrdenListas[idx]){
case 0: linea[1] = "Crescente"; break;
case 1: linea[1] = "Decrescente"; break;
case 2: linea[1] = "Aleatorio"; break;
default: linea[1] = "No especificado" ; break;
}
linea[2] = Convert.ToString(LongitudListas[idx]);
}
}
我已经看到引用文献“如果使用变量但可能未初始化,则会出现编译器错误。但据我所知,变量 string[] (索引:0,1,2)在每种情况下都被初始化,除了 numlistas = 0(numlistas 是一个类参数,其值应该 >=1)。
我还尝试将第 (1) 行和 (2) 行更改为:
(1) List<string> linea;
(2) linea.Add(Convert.ToString(idx));
但同样的错误(当我尝试更改第 (1) 行和第 (2) 行时,我将以下所有行作为注释。
提前感谢您的每一次帮助
最佳答案
就这样做:
string[] linea = new string[3];//3 is the length of your array
//you can store 3 elements in linea [0] [1] and [2]
关于c# - 使用未分配的局部变量(带有字符串数组的非常简单的函数)。 C#语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9350582/