C# 无法转换类型';字符串';至';System.Collections.Generic.IList<;字符串>;
我不断发现这个错误: “无法将类型“string”转换为 'System.Collections.Generic.IList' 这是我的节目:C# 无法转换类型';字符串';至';System.Collections.Generic.IList<;字符串>;,c#,visual-studio,C#,Visual Studio,我不断发现这个错误: “无法将类型“string”转换为 'System.Collections.Generic.IList' 这是我的节目: class Program { static void Main(string[] args) { List<string> list = new List<string>(); list.Add("a"); list.Add("b"); l
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string>();
list.Add("a");
list.Add("b");
list.Add("c");
list.Add("d");
foreach (IList<string> name in list )
{
Console.WriteLine(String.Format("{{{0} {1} {2}}}", list[0], list[1], list[2]));
类程序
{
静态void Main(字符串[]参数)
{
列表=新列表();
列表。添加(“a”);
列表。添加(“b”);
列表。添加(“c”);
列表。添加(“d”);
foreach(列表中的IList名称)
{
Console.WriteLine(String.Format(“{{{0}{1}{2}}}”,list[0],list[1],list[2]);
将foreach(列表中的IList名称)
更改为foreach(列表中的字符串名称)
foreach声明中的第一个标记是要枚举的集合元素的类型
您还可以使用var
关键字让编译器在编译期间计算出类型(同时仍然可以从name
变量的静态类型中获益):foreach(列表中的var name)
更改循环
foreach(string name in list)
{
Console.WriteLine(name);
}
你应该这样做吗
foreach (string name in list )
您的问题是
列表
包含字符串
而不是IList
将for循环更改为:
foreach (string name in list )
{
Console.WriteLine(name);
}
或者丢失
foreach
,只需离开控制台。Writeline
在那里您有一个列表,并且在该列表中添加了4个字符串。该列表是字符串列表,而不是字符串列表
我猜你的意思是(因为你正在用.Format
做一些事情)
在for each循环中,删除
IList
并使用String
foreach(String name in list)
{
Console.WriteLine(String.Format("{{{0} {1} {2}}}", list[0], list[1], list[2]));
}
您需要的输出是什么?foreach循环中还有其他内容吗?您忽略了结束
}
。
foreach(string name in list) {
Console.WriteLine(
string.Format("{{{0} {1} {2}}}", name[0], name[1], name[2]));
}
foreach(String name in list)
{
Console.WriteLine(String.Format("{{{0} {1} {2}}}", list[0], list[1], list[2]));
}