我最近开始学习 C#,必须编写一个程序来打印序列 2, -3, 4, -5, 6, -7, ... 的前 10 个成员;但我收到一个我不明白的错误。
这是我的代码:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class PrintFirst10Elements
{
static void Main(string[] args)
{
List<int> numberList = new List<int>() { 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, };
var firstFiveItems = List.Take(10); // error here on the call to Take
}
}
错误信息是:
Using the generic type 'System.Collections.Generic.List' requires 1 type arguments.
“1 类型参数”是什么意思?所有元素都是整数。
请您参考如下方法:
这里发生了一些事情:
- 正如@Gunther34567 所指出的,您正在尝试调用
Take扩展方法,就好像它是一个静态方法一样。作为扩展方法,您需要使用Take的实例而不是类本身来调用List<int>——因此numberList.Take(10)而不是List<int>.Take(10)。 - 即使
Take是静态方法,您也会尝试使用无效类调用它。List不是一个有效的类:您宁愿需要List<int>,如我上面所示。这就是您看到的错误消息试图解释的内容——其中<int>是必需的类型参数。
此外,对于由 firstFiveItems 设置的变量(与 Take(10) 相比),Take(5) 是一个非常容易混淆的名称。
