目标数组不够长.检查destinatex和长度以及数组';s的下限
本文关键字:数组 检查 不够 destinatex 目标 | 更新日期: 2023-09-27 18:29:08
我有一个类,代码如下:
Array tags;
if (lines.Length > 0)
{
configText = lines[0];
tags = new Array[lines.Length];
lines.CopyTo(tags,1);
}
这里我得到以下错误:
目标数组不够长。检查destndex和长度数组的下限。
方法:
private bool ReadPointListFile(string fileName) {
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(fileName);
string configText = string.Empty;
if (lines.Length > 0)
{
configText = lines[0];
tags = new Array[lines.Length];
lines.CopyTo(tags,1);
}
else
lines.CopyTo(tags,0);
GetConfigurationInfo(lines[0], out this.sInterval, out this.dataAggregate);
return true;
}
它将从1索引开始复制,而不是从零索引开始,这会造成问题。尝试
lines.CopyTo(tags,0);
标记是数组对象的数组,这可能不是您想要的。若要从字符串数组(行)复制,目标数组也应该是字符串数组。所以,在您声明标记的地方,它应该是string[] tags;
在您的if块中,它应该是tags = new string[lines.Length];
这是关于类型和ArrayTypeMismatchException的部分。
现在,如果您打算复制除第一个元素之外的所有元素,则不能使用CopyTo(tags, 1)
,因为1表示目标数组。它指示从何处开始写入值。这就是为什么你有例外。相反,只需循环:for(int i=1;i<lines.Length;i++){tags[i-1]=行[i];}此外,在这种情况下,标记数组少了一个元素,因此可以将其设置为:tags = new string[lines.Length-1];
如果您想跳过行和标记数组中的第一个索引,那么它就是tags = new string[lines.Length];
和tags[i-1] = lines[i];