无法将char类型转换为字符串

时间:2015-05-01 17:02:46

标签: c# arrays

我在C#中处理涉及数组的数据,当我使用foreach循环时它给了我一条消息

  

无法将char类型转换为字符串

int[,] tel = new int[4, 8];
tel[0, 0] = 398;
tel[0, 1] = 3333;
tel[0, 2] = 2883;
tel[0, 3] = 17698;
tel[1, 0] = 1762;
tel[1, 1] = 176925;
tel[1, 2] = 398722;
tel[2, 0] = 38870;
tel[3, 1] = 30439;

foreach (string t in tel.ToString())
{
    Console.WriteLine(tel +" " +"is calling");
    Console.ReadKey();
}

2 个答案:

答案 0 :(得分:3)

这是因为当foreach超过string每个值为char时,你会尝试将它们转换为string

 foreach(string t in tel.ToString())

但您不太可能想foreach tel.ToString(),因为它会返回telSystem.Int32[,])类型的名称。相反,您可能希望迭代tel

中的所有值
for(int i=0; i<4; i++)
{
    for(int j=0; j<8; j++)
    {
        Console.WriteLine(tel[i,j] +" is calling");
        Console.ReadKey();
    }
}

或者

foreach(int t in tel)
{
    Console.WriteLine(t +" is calling");
    Console.ReadKey();
}

请注意,由于您没有为tel数组中的所有位置指定值,因此某些值将为零。

答案 1 :(得分:0)

迭代数组中的值,如下所示:

int rowLength = tel.GetLength(0);
int colLength = tel.GetLength(1);

for (int i = 0; i < rowLength; i++)
{
    for (int j = 0; j < colLength; j++)
    {
        Console.WriteLine(tel[i, j]+" is calling");
    }
}
Console.ReadLine();
相关问题