C# 函数链
为什么我在以下声明中收到错误?
List<int> intrs = new List<int>().AddRange(new int[]{1,2,3,45});
错误:无法将类型 void 转换为 List?
Why do i receive error in the following declaration ?
List<int> intrs = new List<int>().AddRange(new int[]{1,2,3,45});
Error :Can not convert type void to List ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
因为 AddRange 函数不返回值。您可能需要分两步执行此操作:
Because AddRange function does not return a value. You might need to perform this in two steps:
您还可以使用集合初始值设定项(假设 C# 3.0+)。
280Z28 编辑:这适用于任何具有
Add
方法的内容。构造函数括号是可选的 - 如果您想将诸如容量之类的东西传递给构造函数,您可以使用List(capacity)
而不仅仅是List< /code> 写在上面。
以下是有关对象和集合初始值设定项的详细信息的 MSDN 参考。
You could also use a collection initializer (assuming C# 3.0+).
Edit by 280Z28: This works for anything with an
Add
method. The constructor parenthesis are optional - if you want to pass thing to a constructor such as the capacity, you can do so withList<int>(capacity)
instead of justList<int>
written above.Here's an MSDN reference for details on the Object and Collection Initializers.
因为 AddRange 修改指定的列表,而不是返回一个新列表添加的项目。为了表明这一点,它返回
void
。试试这个:
如果您想创建一个新列表而不修改原始列表,您可以使用
Because AddRange modifies the specified list instead of returning a new list with the added items. To indicate this, it returns
void
.Try this:
If you want to create a new list without modifying the original list, you can use LINQ:
AddRange 不会返回已添加项目的列表(与 StringBuilder 不同)。你需要做这样的事情:
AddRange does not return the list it has added items to (unlike StringBuilder). You need to do something like this:
AddRange() 声明为:
它不返回列表。
AddRange() is declared as:
It does not return the list.
顺便说一句,在 C# 3.x(不确定 2.0)中,您可以执行以下任一操作:
除了其他答案之外,您还可以添加自己的扩展方法来添加范围和返回列表(这并不是一个好的做法)。
By the way in C# 3.x (not sure about 2.0) you can do either of
Besides other answers, you can add your own extension method that will add range and return list (not that it's a good practice).
顺便说一句,如果你已经声明了 intrs,你可以用括号来完成它:
但是,我更喜欢初始化语法。
BTW, if you had already declared intrs, you could have done it with parentheses:
However, I like the initialization syntax better.
尽管其他人已经提到 AddRange 不返回值,但根据替代方案给出的示例,还应该记住,除了前面提到的 .NET 3.5 代码之外,List 的构造函数还将采用 T 的 IEnumerable +
例如:
Although others have already mentioned that AddRange does not return a value, based on the samples given for alternatives it should also be remembered that the constructor of List will take an IEnumerable of T as well in addition to the code previously mentioned that is .NET 3.5+
For example:
还有另一种方法。
There is yet another way.