使用Take获取通用列表的前10个元素时出错

时间:2014-12-29 22:48:54

标签: c# list

我最近开始学习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类型参数”是什么意思?所有元素都是整数。

2 个答案:

答案 0 :(得分:2)

你有几件事情在这里:

  1. 正如@ Gunther34567指出的那样,您试图将Take扩展方法称为静态方法。作为一种扩展方法,您需要使用Take的实例而不是类本身来调用List<int> - 所以numberList.Take(10)而不是List<int>.Take(10)
  2. 即使Take是静态方法,您也会尝试使用无效的类来调用它。 List不是有效的类:如上所示,您宁愿需要List<int>。这就是您看到的错误消息试图解释的内容 - <int>将是必需的类型参数。
  3. 此外,firstFiveItems对于由Take(10)(与Take(5))设置的变量的名称相当混淆。

答案 1 :(得分:1)

var firstFiveItems = List.Take(10);更改为var firstFiveItems = numberList.Take(10);,它将按照您希望的方式运行。

正如Gunther34567所说,Take methodList class的扩展方法。