【问题标题】:Cannot implicitly convert type void to System.Collections.GenericList无法将类型 void 隐式转换为 System.Collections.GenericList
【发布时间】:2019-06-15 11:13:19
【问题描述】:

我遇到了列表问题。 在我的 for 循环中,我试图在某个索引的列表中添加一个元素。

我收到的列表FinalKnotsVector 的错误是:

“无法将类型 'void' 隐式转换为 System.Collections.Generic.List”

有人可以帮助我吗?

{

    [MultiReturn(new[] { "l", "n","FinalKnotsVector"})]
    public static Dictionary<string, object> InLength(List<double> Initialknots, int p, List<double> KnotInserted)
    {
        int l;                                      //OUTPUT: Length of the initial knot vector
        l = Initialknots.Count;

        int n;                                      //OUTPUT: Number of initial control points 
        n = l - 1 - p;

        List<double> FinalKnotsVector = new List<double>();

        for (int i = 1; i < KnotInserted.Count; i++)
        {
            FinalKnotsVector=Initialknots.Insert(i, KnotInserted[i]);
        }


        var d = new Dictionary<string, object>();
        d.Add("l", l);
        d.Add("n", n);
        d.Add("FinalKnotsVector", FinalKnotsVector);
        return d;

    }

}

}

【问题讨论】:

  • Initialknots.Insert 修改Initialknots 列表并且不返回任何内容。所以不能将返回值赋给FinalKnotsVector
  • Initialknots.Insert 返回类型为 void。您不能将 void 分配给列表
  • 你应该在for循环中说明你想做什么。
  • @poke 嗨,谢谢。我想做的是在 Initialknots 中插入一些从 KnotInserted 通过 for 循环获取的值。我能怎么做?我想要一个新的列表而不是一个空的列表
  • 复制Initialknots 列表,然后附加到它:FinalKnotsVector = new List&lt;double&gt;(Initialknots);,然后在循环内:FinalKnotsVector.Add(KnotInserted[i]);

标签: c# list void


【解决方案1】:

你应该这样做:

List<double> FinalKnotsVector = new List<double>(Initialknots);
foreach (var value in KnotInserted)
{
    FinalKnotsVector.Insert(FinalKnotsVector.IndexOf(value), value);
}

这是简单直接的方法。看看这是否符合您的要求。

请注意,我没有更改 Initialknots在您的代码中,但是您尝试将项目插入其中)。如果您还需要更改它,请先更改Initialknots,然后您可以创建FinalKnotsVector,将Initialknots 传递给构造函数,如下所示:

foreach (var value in KnotInserted)
{
    Initialknots.Insert(Initialknots.IndexOf(value), value);
}
List<double> FinalKnotsVector = new List<double>(Initialknots);

【讨论】:

  • 嗨@bahrom 很抱歉再次打扰,但现在我试图在 FinalKnotsVector 中找到一个值的索引,但我遇到了错误“Argument 1:cannot convert from System.Collections.Generic .List 到 'double'。我以前这样写:k = FinalKnotsVector.IndexOf(KnotInserted);
猜你喜欢
  • 2013-02-22
  • 1970-01-01
  • 1970-01-01
  • 2014-04-14
  • 2016-02-17
  • 2015-04-26
  • 2015-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多