我最近开始学习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
}
}
错误消息是:
使用泛型类型'System.Collections.Generic.List'需要1个类型参数。
“1类型参数”是什么意思?所有元素都是整数。
答案 0 :(得分:2)
你有几件事情在这里:
Take
扩展方法称为静态方法。作为一种扩展方法,您需要使用Take
的实例而不是类本身来调用List<int>
- 所以numberList.Take(10)
而不是List<int>.Take(10)
。Take
是静态方法,您也会尝试使用无效的类来调用它。 List
不是有效的类:如上所示,您宁愿需要List<int>
。这就是您看到的错误消息试图解释的内容 - <int>
将是必需的类型参数。此外,firstFiveItems
对于由Take(10)
(与Take(5)
)设置的变量的名称相当混淆。
答案 1 :(得分:1)
将var firstFiveItems = List.Take(10);
更改为var firstFiveItems = numberList.Take(10);
,它将按照您希望的方式运行。
正如Gunther34567所说,Take
method是List
class的扩展方法。