繁体   English   中英

C#中的索引超出范围异常

[英]Index out of bounds exception in c#

我的程序中有以下代码,这些代码在yearList.SetValue(years [count],count);行中抛出索引超出范围的异常;

protected void invoiceYear_DataBound(object sender, EventArgs e)
        {
           //invoiceYear.SelectedItem.Value= GetYearRange();
            String[] years = GetYearRange().Split(new char[] { '[', ',', ']',' ' });
            ListItem [] yearList = new ListItem[]{};
            System.Diagnostics.Debug.WriteLine("years-->" + years.Length);
            for (int i = 0; i < years.Length; i++)
            {
                System.Diagnostics.Debug.WriteLine("years-->" + years.GetValue(i));

            }
            int count = 0;
            foreach (String str in years)
            {
                if (string.IsNullOrEmpty(str))
                    System.Diagnostics.Debug.WriteLine("empty");
                else
                {
                    yearList.SetValue(years[count], count);
                    count++;
                }
            }

            //System.Diagnostics.Debug.WriteLine("yearList-->" + yearList.GetValue(0));
            //invoiceYear.Items.AddRange(yearList);
        }

您没有问过问题,所以我猜您的问题就是“为什么?”

yearList被定义为一个空数组:

ListItem [] yearList = new ListItem[]{};

它的长度始终为零。 因此,您无法设置任何元素,因为它没有要设置的元素。

更新

您现在已经问:“但是我不知道如何声明动态数组?”

.NET中没有动态数组。 根据您的方案,您有许多不同的收集类型。 我建议List<ListItem>可能是您想要的。

List<ListItem> yearList = new List<ListItem>(); // An empty list

然后

yearList.Add(years[count]); // Adds an element to the end of the list.

另外,整个循环最好写成:

        foreach (String str in years)
        {
            if (string.IsNullOrEmpty(str))
                System.Diagnostics.Debug.WriteLine("empty");
            else
            {
                yearList.Add(str);
            }
        }

这样,您就不必担心count ,也不必担心步数变高(因为只有在str包含某些内容时才增加计数-可能不是您想要的)

更新2并且,如果您迫切需要最后一个数组,则始终可以使用yearList.ToArray()将列表隐藏到数组中,但是请记住using System.Linq;进行添加using System.Linq; 在文件的顶部,因为它是LINQ提供的扩展方法,而不是List类本身的一部分。

如果要保持计数器,为什么只使用For时为什么要使用Foreach循环?

        foreach (var int i = 0; i < years.Length; i++)
        {
            if (string.IsNullOrEmpty(years[i]))
                System.Diagnostics.Debug.WriteLine("empty");
            else
            {
                yearList.SetValue(years[i], i);
            }
        }

我不知道您的目标是什么,并且我对ListItem没有任何经验,但是您是否考虑过这种方法:

string[] yearList = years.Where(y => !string.IsNullOrEmpty(y)).ToArray();

这将创建一个不为空或为空的所有年份的数组。 它还取决于您如何使用列表,以了解它是否有用。 如果不需要是数组,那么您甚至可以这样做:

var yearList = years.Where(y => !string.IsNullOrEmpty(y));

请注意,就诊断输出或使用ListItem而言,这些解决方案并不能完全执行您的代码。 这是否是您的选择还取决于所使用的.net版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM