为什么我收到此编译错误?

时间:2011-12-14 15:09:09

标签: c#

为什么我不能使用下面的选项#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);
        }
    } 

12 个答案:

答案 0 :(得分:14)

List<T>.Add返回void。您的代码失败的方式与失败的方式相同:

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

然而,使用集合初始化程序进行救援的C#3:

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

答案 1 :(得分:5)

因为.Add()返回void类型而不是List。但是你可以这样做

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

答案 2 :(得分: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);
            }
        }

答案 3 :(得分: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" });

答案 4 :(得分:2)

您会看到此错误,因为Add方法不会返回任何内容。您可以将此行更改为:

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

答案 5 :(得分:1)

new List<string>().Add("This give compilation Error")

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

答案 6 :(得分:1)

作为操作的结果,

List<T>.Add(T someItem)没有返回对列表的引用,它返回void

答案 7 :(得分:1)

List.Add会返回void,这就是您传递给SomeMethod的内容。显然这不起作用。

答案 8 :(得分:1)

因为Add方法返回类型是Void而您希望它返回collection.Check文档http://msdn.microsoft.com/en-us/library/3wcytfd1.aspx public void添加(     T项目 )

答案 9 :(得分:1)

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

答案 10 :(得分:0)

因为在您的第一个选项中,您将Add()方法的返回值传递给SomeMethod(),而不是实际的List<string>对象。

答案 11 :(得分:0)

AFAIK,泛型List的Add()方法不返回int,它是void。

相关问题