不能char类型转换为字符串 [英] cannot convert type char to string

查看:104
本文介绍了不能char类型转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的,涉及阵列在C#中的数据,当我使用foreach循环它给了我一个消息


  

无法char类型转换为字符串


  INT [,] TEL =新INT [4,8]。
电话[0,0] = 398;
电话:[0,1] = 3333;
电话[0,2] = 2883;
电话[0,3] = 17698;
电话[1,0] = 1762;
电话[1,1] = 176925;
电话[1,2] = 398722;
电话[2,0] = 38870;
电话:[3,1] = 30439;的foreach(字符串吨tel.ToString())
{
    Console.WriteLine(电话:++呼唤);
    Console.ReadKey();
}


解决方案

这是监守,当你的foreach 超过字符串的每个值将是字符,但你想将它们转换成字符串

 的foreach(在tel.ToString串T())

但它不太可能,你希望的foreach tel.ToString()作为返回的名称电话类型 System.Int32 [,] )。相反,你可能要遍历所有的值电话

 的for(int i = 0;我4;;我++)
{
    对于(INT J = 0; J< 8; J ++)
    {
        Console.WriteLine(电话:[I,J] +呼唤);
        Console.ReadKey();
    }
}

或者

 的foreach(在电话INT T)
{
    Console.WriteLine(T +呼唤);
    Console.ReadKey();
}

请注意,某些值将是零,因为你不分配值在电话所有的位置阵列。

I'm doing data involving arrays in C#, when I use the foreach loop it gave me an message

cannot convert type char to string

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

解决方案

That is becuase when you foreach over a string each value will be a char, but you are trying to cast them to string.

 foreach(string t in tel.ToString())

But it's unlikely that you want to foreach on tel.ToString() as the will return the name of the type of tel (System.Int32[,]). Instead you probably want to iterate all the values in tel

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

Or

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

Note that some of the values will be zero since you do not assign values to all the positions in the tel array.

这篇关于不能char类型转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆