为什么我不能使用下面的选项#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);
}
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 14
List<T>.Add回报void.您的代码失败的方式与失败的方式相同:
List<string> list = new List<string>().Add("This wouldn't work");
Run Code Online (Sandbox Code Playgroud)
但是,使用集合初始化程序进行救援的C#3:
SomeMethod(new List<string> { "Woot!" });
Run Code Online (Sandbox Code Playgroud)
因为.Add()返回void类型而不是List.但是你可以这样做
SomeMethod(new List<string>() { "This give compilation Error" });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
273 次 |
| 最近记录: |