为什么我会遇到这个编译错误?

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);
        }
    } 
12个回答

14

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

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

然而,C# 3带来了集合初始化器的救赎:

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

5
因为 .Add() 返回的是 void 类型而不是 List。但是你可以这样做:
SomeMethod(new List<string>() { "This give compilation Error" });

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

其他回复是正确的,因为它们指出了我所做的愚蠢之事,但这才是我真正想要做的。谢谢大家。 - palm snow

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" });

2
你看到这个错误是因为 Add 方法没有返回任何内容。你可以把这行改成:
SomeMethod(new List<string>(){"This won't give compilation Error"});

1

List<T>.Add(T someItem) 方法执行后不会返回列表的引用,而是返回 void


1

List.Add 返回 void,这就是你传递到 SomeMethod 中的内容。显然这样做是行不通的。


1

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

返回类型为 void,但方法 SomeMethod 期望一个 List<string>


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

我不确定为什么这个回答会被负评,这个回答是完全有效的,并且正是Dewasish所建议的。 - Security Hound

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接