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

本文关键字:元素 出错 Take 获取 泛型 列表 使用 | 更新日期: 2023-09-27 18:35:40

我最近开始学习C#,必须制作一个程序来打印序列的前10个成员2, -3, 4, -5, 6, -7, ...;但是我得到了一个我不明白的错误。

这是我的代码:

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 类型参数"是什么意思?所有元素都是整数。

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

你这里有几件事:

  1. 正如@Gunther34567指出的,您正在尝试调用Take扩展方法,就好像它是一个静态方法一样。 作为扩展方法,您需要使用 List<int> 的实例而不是类本身来调用 Take – 因此numberList.Take(10)而不是List<int>.Take(10)
  2. 即使Take是一个静态方法,您也会尝试使用无效类来调用它。 List 不是一个有效的类:你宁愿需要List<int>,如我上面所示。 这就是您看到的错误消息试图解释的内容 - 其中<int>是必需的类型参数。

此外,对于由 Take(10) 设置的变量来说,firstFiveItems是一个非常令人困惑的名称(与 Take(5) )。

var firstFiveItems = List.Take(10);更改为var firstFiveItems = numberList.Take(10);,它将按照您想要的方式工作。

正如 Gunther34567 已经说过的,Take 方法是 List 类的扩展方法。