C#中的索引错误,数组应返回空数组,但返回范围超出范围 [英] Index Error in C# Where Array Should Return Empty Array But Returns Out Of Range
问题描述
我是C#的新手,并且遇到一个错误,我需要让DataPoints数组返回空值,但是由于任何原因我都遇到了此错误.我在这里做什么错了?
I'm new to C# and having an error where I need to have the DataPoints array to return empty but I'm getting this error for whatever reason. What am I doing wrong here?
索引超出范围.必须为非负数且小于\ r \ n参数名称:index"
Index was out of range. Must be non-negative and less than the size of the collection.\r\nParameter name: index"
var DataPoints = new DataPoints();
// Generate DataPoints (or something similar) from the newly constructed WspViewList.
foreach (WspViewRow row in dataPointBuilder)
{
var dataPointList = row.OriginalData.TrimStart('[').TrimEnd(']').Split(',').ToList();
DataPoints.labels.Add(dataPointList[1]);
for (var index = 2; index< dataPointList.Count; index++)
{
var dataPoint = dataPointList[index];
if (string.IsNullOrEmpty(dataPoint))
continue;
ChartDataObject cdo;
if (DataPoints.datasets.Count <= index - 2)
{
cdo = new ChartDataObject();
DataPoints.datasets.Add(cdo);
cdo.label = ColumnObjects[index].propertyName;
}
else
cdo = DataPoints.datasets[index - 2];
cdo.data.Add(dataPoint);
DataPoints.datasets[index - 2] = cdo;
}
DataPointAPI DataPointResponse = new DataPointAPI()
{
data = DataPoints,
};
dataset.Add(DataPointResponse);
}
// Set some class field to contain these datapoints
ChartData = dataset;
推荐答案
当您获得异常时,您可以获取发生异常的行号.您还可以使用debbuger查看是否错过了某些内容.
When you get the exception, you could get the line number where it happend. You can also use debbuger to see if you miss something.
实际上,您尝试通过异地访问数组/列表中的数据而引发异常.请记住,索引从 0 到阵列的总长度-1
Actually your exception is throwed by trying to accessing data outsite your array / list. Remember that your index is starting from 0 to total length of your array - 1
var array = new []{1,2,3};
array[0] => 1
array[1] => 2
array[2] => 3
array[3] => out of range
这篇关于C#中的索引错误,数组应返回空数组,但返回范围超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!