在索引0处将元素插入List:“无法转换”

时间:2014-08-08 12:47:07

标签: c# list indexing

我找到了如何制作列表,但我似乎无法插入新值。

List<Tuple<int,int>> snake = new List<Tuple<int, int>>();
...
snake.Insert(Tuple.Create(x, y), 0);

它会产生一些错误: 参数1:无法转换为System.Tuple&#39;到&#39; int&#39; 参数2:无法转换为&#39; int&#39;到&#39; System.Tuple&#39;

如何允许将值插入索引0?

3 个答案:

答案 0 :(得分:4)

如果您咨询documentation,您会看到Insert的方法签名看起来像这样:

public void Insert(
    int index,
    T item
)

您混淆了代码中参数的顺序。您需要提供索引作为第一个参数:

snake.Insert(0, Tuple.Create(x, y));

答案 1 :(得分:1)

你搞砸了插入方法 - 它应该是这样的:

  List<Tuple<int,int>> snake = new List<Tuple<int, int>>();

    snake.Insert(0, Tuple.Create(x, y));

List.Insert Method

答案 2 :(得分:1)

insert ist

的语法
public void Insert(
    int index,
    T item
)

在你的情况下:

snake.Insert(0, Tuple.Create(x, y));