C# 测试空数组索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/922858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:17:29  来源:igfitidea点击:

Testing null array index

c#arrays

提问by Carlo

Here's the thing:

事情是这样的:

object[] arrayText = new object[1];

if (arrayText[1] == null)
{
    MessageBox.Show("Is null");
}

We know that is going to be null, but it throws an exception, but I don't want to handle it in a try/catch block because that is nested in a loop and try/catch will slow it down, also it doesn't look really good:

我们知道它将为空,但它会引发异常,但我不想在 try/catch 块中处理它,因为它嵌套在循环中并且 try/catch 会减慢它的速度,它也不会'看起来真的很好:

object[] arrayText = new object[1];
try
{
    if (arrayText[1] == null)
    {

    }
}
catch (Exception ex)
{
    MessageBox.Show("Is null");
}

Thanks for you suggestions!

谢谢你的建议!

采纳答案by Lucero

nullis not the problem here, but the index is invalid. Arrays in C# are 0-based, so if you create an array with 1 element, only index 0is valid:

null不是这里的问题,而是索引无效。C# 中的数组是基于 0 的,因此如果您创建一个包含 1 个元素的数组,则只有索引0有效:

array[0] == null

You can avoid that by checking the bounds manually before accessing the index:

您可以通过在访问索引之前手动检查边界来避免这种情况:

if (index < array.Length) {
    // access array[index] here
} else {
    // no exception, this is the "invalid" case
}

回答by Adam Robinson

You're accessing an index that's outside the array's bounds. The array initializer takes a number for the number of elements, not the maximum index (like VB.NET). Since arrays are zero-based, your maximum index is 0 in this case.

您正在访问数组边界之外的索引。数组初始值设定项采用元素数量的数字,而不是最大索引(如 VB.NET)。由于数组是从零开始的,因此在这种情况下,您的最大索引为 0。

回答by Gromer

object[] arrayText = new object[1];

if (arrayText[0] == null)
{
    MessageBox.Show("Is null");
}

Try that? Arrays are 0 based, so trying to access arrayText[1] will give you an OutOfBoundsException. And the try/catch won't really impact your performance that much there, there isn't much in the stack at that point.

试试那个?数组是基于 0 的,所以尝试访问 arrayText[1] 会给你一个 OutOfBoundsException。并且 try/catch 不会真正影响您的性能,此时堆栈中没有太多东西。

回答by Dave Bauman

Check the .Length of the array inside the loop, or better yet, set your loop parameters to be limited to the length of the array.

检查循环内数组的 .Length ,或者更好的是,将循环参数设置为限制为数组的长度。

object[] arrayText = new object[1];
for (int i = 0; i < arrayText.Length; i++)
{
    doWork(arrayText[i]);
}

回答by David McEwing

If you read the description on the exception that is being thrown you will see that it is "Index was outside the bounds of the array."

如果您阅读有关正在引发的异常的描述,您将看到它是“索引超出数组范围”。

The new object[1]indicates that the array has one element. (1 is the count) However C# array's start indexing at 0 not 1 so an array of one element is index 0. So arrayText[0]will return null but arrayText[1]will throw an exception.

new object[1]表示该阵列具有一个元素。(1 是计数)但是,C# 数组的起始索引为 0 而不是 1,因此一个元素的数组的索引为 0。因此arrayText[0]将返回 null 但arrayText[1]会引发异常。

回答by stuck

I think the problem is not that arrayText1is null, it's that arrayText1doesnt exist - so you should get an IndexOutOfRangeException and not a null

我认为问题不在于 arrayText 1为空,而是 arrayText 1不存在 - 所以你应该得到一个 IndexOutOfRangeException 而不是空

if you're up a creek and cant easily change the code to verify the lenght you might consider adding a function that inspects the Length property (see snippit below) or overloading operator[]... both of these are a little gross but if you're in a pickle... :)

如果您在一条小河上并且无法轻松更改代码以验证长度,您可能会考虑添加一个检查 Length 属性的函数(请参阅下面的代码段)或重载运算符[]...你在泡菜中...... :)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace array
{
    class Program
    {
        static object Index(object [] array, int idx)
        {
            if (idx >= array.Length)
                return null;
            else
                return array[idx];
        }
        static void Main(string[] args)
        {
            object[] blah = new object[10];
            object o = Index(blah, 10);
        }
    }
}

回答by Popa Alin

I recently needed to find out if values in a struct array are "filled" or not at a given index. Check this out:

我最近需要找出结构数组中的值是否在给定索引处“填充”。看一下这个:

//the struct holding the properties:
struct Cities
        {
            public string name;

            public int inhabitansNumber;
        }

    Cities[] cities = new Cities[500]; // the struct array holding the cities

    int i = 0;
                        for (i = 0; i < cities.Length; ++i)
                        {
                            if (cities[i].Equals(default(Cities)))
                            {
                                Console.WriteLine("Please enter the city name:");
                                cities[i].name = Console.ReadLine();
                                Console.WriteLine("Please enter population:");
                                cities[i].inhabitansNumber = Convert.ToInt32(Console.ReadLine());
                                Console.WriteLine("Values added successfuly!");
                            }
                        }