【问题标题】:Insert an element into a List at index 0: "Cannot convert"将元素插入到索引 0 处的列表中:“无法转换”
【发布时间】:2014-10-01 22:58:28
【问题描述】:

我知道如何制作列表,但我似乎无法插入新值。

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

它会产生一些错误: 参数 1:无法从 'System.Tuple' 转换为 'int' 参数 2:无法从 'int' 转换为 'System.Tuple'

我该怎么做才能允许将值插入索引 0?

【问题讨论】:

标签: c# list indexing


【解决方案1】:

你弄乱了插入方法——应该是这样的:

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

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

List.Insert Method

【讨论】:

    【解决方案2】:

    如果您查阅documentation,您将看到Insert 的方法签名如下所示:

    public void Insert(
        int index,
        T item
    )
    

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

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

    【讨论】:

      【解决方案3】:

      insert的语法

      public void Insert(
          int index,
          T item
      )
      

      在你的情况下:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-19
        • 1970-01-01
        • 1970-01-01
        • 2020-08-05
        • 1970-01-01
        • 2011-11-14
        • 2016-09-04
        • 1970-01-01
        相关资源
        最近更新 更多