开发者

Cannot convert type 'string' to 'System.Collections.Generic.IList<string>

开发者 https://www.devze.com 2023-03-11 00:29 出处:网络
I keep gettig this error: \"Canno开发者_如何学Pythont convert type \'string\' to \'System.Collections.Generic.IList\"

I keep gettig this error:

"Canno开发者_如何学Pythont convert type 'string' to 'System.Collections.Generic.IList"

Here is my program:

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


You have a list, and to that list you've added 4 strings. The list is a list-of-strings, not a a list-of-lists-of-strings.

I suspect you mean (since you are doing something with .Format)

List<string> list = new List<string>(); 
// 4 x Add
Console.WriteLine(String.Format("{{{0} {1} {2}}}", list.ToArray()));

alternatively, if you mean the first 3 characters in each (which WON'T WORK for your sample data, since each is a string of length 1):

foreach(string name in list) {
    Console.WriteLine(
        string.Format("{{{0} {1} {2}}}", name[0], name[1], name[2]));
}


Change the foreach (IList<string> name in list ) to foreach (string name in list )

The first token inside the foreach declaration is the type of the elements of the collection you are enumerating.

You can also use the var keyword to let the compiler figure out the type during compilation (while still getting benefits of static typing of the name variable): foreach (var name in list)


in for each loop remove IList<String> and use String

 foreach(String name in list)
 {
    Console.WriteLine(String.Format("{{{0} {1} {2}}}", list[0], list[1], list[2]));
 }


Change your loop

foreach(string name in list)
{
    Console.WriteLine(name);
}


Should you be doing this?

foreach (string name in list )


Your problem is that the list containsstrings not IList<string>

Either change the for loop to:

foreach (string name in list ) 
    {
        Console.WriteLine(name);
    }

or lose the foreach and just leave the Console.Writeline in there

0

精彩评论

暂无评论...
验证码 换一张
取 消