【问题标题】:cannot convert type char to string无法将 char 类型转换为字符串
【发布时间】:2015-05-01 17:02:46
【问题描述】:

我在 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();
}

【问题讨论】:

    标签: c# arrays


    【解决方案1】:

    这是因为当您 foreach 超过 string 时,每个值都将是 char,但您正试图将它们转换为 string

     foreach(string t in tel.ToString())
    

    但您不太可能想在tel.ToString() 上使用foreach,因为这将返回tel (System.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 数组中的所有位置分配值。

    【讨论】:

    • 需要注意的是 tel.ToString() 返回的是类型名称,而不是数组中的任何值。 foreach 起作用的唯一原因是字符串可以隐式转换为 IEnumerable 的 char 数组。它抱怨通过该链转换回前面的字符串...
    • @RonBeyer 我确实提到tel.ToString() 返回类型名称。但要清楚,我已经包含了返回的实际字符串。
    【解决方案2】:

    像这样遍历数组中的值:

    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();
    

    【讨论】:

      猜你喜欢
      • 2014-02-04
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多