我收到以下错误消息,代码如下。我认为数据类型
List<double>
与 double[]
相同,但 C# 要求使用第一种语法将其实例化,以便变量作为对象工作。我做错了什么还是我的想法错了?
Cannot implicitily convert type `double[]` to `System.Collections.Generic.List<double>`
代码:
private void RunScript(List<Curve> crv, double nb, ref object DivPts)
{
List<double> nbtemp = new List<double>();
List<double> Divpt = new List<double>();
for(int i = 0; i < crv.Count;i = i + 2)
{
nbtemp = crv[i].DivideByLength(nb, true);
}
Divpt = nbtemp;
不,列表不是数组,尽管概念有些相似。 C#中的
List<T>
类实际上是通过幕后数组实现的。
如果你想从数组中设置一个列表,你可以使用这样的东西:
nbtemp = new List<double>(crv[i].DivideByLength(nb, true));
这将创建一个新的列表,并用数组初始化它。如果您想将数组追加到现有列表中,还可以使用
AddRange
的 List
方法,如下所示:
nbtemp.AddRange(crv[i].DivideByLength(nb, true));
你无法从Array转换为List,但你可以轻松调用:
nbtemp = crv[i].DivideByLength(nb, true).ToList();
或者,由于您已经定义了列表,您也可以:
nbtemp.AddRange(crv[i].DivideByLength(nb, true));
您正在使用赋值,很难判断 DivideByLength 返回什么,如果是单个值,则使用:
nbtemp.Add(crv[i].DivideByLength(nb, true));
否则,如果它返回数组,请尝试更改定义以允许列表包含数组:
List<double[]> nbtemp = new List<double[]>();
请注意,
List
不等于 double[]
。 List
具有许多简单数组所没有的功能。您可以通过查看公开公开方法的两篇不同的 MSDN 文章来了解差异。
此外,您的 for 循环目前正在使用赋值。如果不更改这部分代码,您只需将 for 循环的最后一次迭代分配给变量 nbtemp (假设您删除了错误)
它们都是
IEnumerable
的实现者,但它们不是等价的类型。您将需要执行强制转换或方法调用。在上面的代码中,我会说你需要:
nbtemp = (crv[i].DivideByLength(nb, true)).ToList();
或
nbtemp.AddRange(crv[i].DivideByLength(nb, true));
crv[i].DivideByLength(nb, true).toArray()