2011-12-14 86 views
3

爲什麼我不能使用下面的選項#1。選項2正常工作爲什麼我得到這個編譯錯誤?

class Program 
    { 
     static void Main() 
     { 
      //Option 1 
      //Error 1 The best overloaded method match for 'ConsoleApplication2.Program.SomeMethod(System.Collections.Generic.List<string>)' has some invalid argument 
      //Error 2 Argument 1: cannot convert from 'void' to 'System.Collections.Generic.List<string>' 
      SomeMethod(new List<string>().Add("This give compilation Error")); 

      //Option 2 
      List<string> MyMessages = new List<string>(); 
      MyMessages.Add("This compiles fine"); 
      SomeMethod(MyMessages); 
     } 

     static void SomeMethod(List<string> Messages) 
     { 
      foreach (string Message in Messages) 
       Console.WriteLine(Message); 
     } 
    } 

回答

4

試試這個:

class Program 
     { 
      static void Main() 
      { 

       //There was a syntax error in your code. It should be declare like this 
       SomeMethod(new List<string>(){("This give compilation Error")}); 

       //Option 2 
       List<string> MyMessages = new List<string>(); 
       MyMessages.Add("This compiles fine"); 
       SomeMethod(MyMessages); 
      } 

      static void SomeMethod(List<string> Messages) 
      { 
       foreach (string Message in Messages) 
        Console.WriteLine(Message); 
      } 
     } 
+0

其他答案是正確的,因爲他們指出我正在做的愚蠢的事情,但這是我真正想做的事情。謝謝全部 – 2011-12-14 15:27:19

14

List<T>.Add返回void。您的代碼以同樣的方式,這將失敗,失敗:

List<string> list = new List<string>().Add("This wouldn't work"); 

然而,C#3與集合初始化救援:

SomeMethod(new List<string> { "Woot!" }); 
3

這是因爲List<T>.Add()方法不返回的元素,你剛剛添加到列表中。它返回void。

但你可以這樣做:

SomeMethod(new List<string>(new[] { "This compiles fine" })); 

或使用集合初始化語法:

SomeMethod(new List<string> { "This compiles fine" }); 

,如果你想多個元素:

SomeMethod(new List<string> { "elem1", "elem2", "elem3" }); 
1
new List<string>().Add("This give compilation Error") 

返回void但方法SomeMethod需要一個List<string>

1

List<T>.Add(T someItem)不返回到列表的引用作爲操作的結果,它返回因爲在你的第一個選項無效

0

,要傳遞的Add()方法的返回到SomeMethod(),不實際的List<string>對象。

1

List.Add返回void這就是你要傳遞給SomeMethod。顯然這不起作用。

5

因爲.Add()返回void類型而不是List。然而,你可以做到這一點

SomeMethod(new List<string>() { "This give compilation Error" }); 
0

據我所知,通用列表的Add()方法不返回一個int,它是無效的。

2

您看到這個錯誤,因爲Add方法不返回任何東西。您可以更改此行:

SomeMethod(new List<string>(){"This won't give compilation Error"}); 
1
SomeMethod(new List<string>() {"This give compilation Error"}); 
+0

我不知道這個原因,這個被賦予了反對票,這個答案是完全有效的,而這正是Dewasish建議。 – 2011-12-14 15:44:19