简体   繁体   English

防止索引超出范围错误

[英]Preventing Index Out of Range Error

I want to write a check for some conditions without having to use try/catch and I want to avoid the possibilities of getting Index Out of Range errors 我想写一些条件下的检查而不必使用try / catch,并且我想避免出现“索引超出范围”错误的可能性

if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
 {                
    if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
       {
           // execute code here
       }
 }

So the problem I am facing is that in the second check I need to see whether I have one Item that is not empty. 因此,我面临的问题是在第二次检查中,我需要查看我是否有一个不为空的商品。 However, If I don't have Element[1] , I get the Index Out of Range exception. 但是,如果我没有Element[1] ,则会得到“索引超出范围”异常。 The problem is that there could be 2 Elements and one(or both) of them may have empty Object arrays. 问题在于可能有2个元素,并且其中一个(或两个元素)可能具有空的Object数组。 The code will have to be executed only if one of thos Item strings is not empty. 仅当项目字符串之一不为空时,才必须执行该代码。

Hopefully, I explained it well. 希望我解释得很好。 How do I go about avoiding getting that exception under any condition? 在任何情况下,如何避免遇到该异常?

Alright, you need some better null checking and some more cautious code here. 好了,您需要一些更好的null检查和一些更谨慎的代码。

if (array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
{                
   if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
   {
       // execute code here
   }
}

is just unacceptable. 是不可接受的。

First, let's null check 首先,让我们进行空检查

if (array != null)
{
    if (array.Element != null)

for simplicity, you could use && 为简单起见,您可以使用&&

if (array != null && array.Element != null)

then, inside that if, we use a for loop ( since you're stuck on arrays ) and null check it 然后,如果在其中,我们使用一个for循环( 因为您被卡在数组上 ),并进行null检查

for (int i = 0; i < array.Element; ++i)
{
    if (array.Element[i] != null && array.Element[i].Object != null)
    {

then, since you have nested arrays, we loop again. 然后,由于您拥有嵌套数组,因此我们再次循环。 This is called a nested loop , and it's generally bad practice, I'll show you why it works in a second. 这被称为嵌套循环 ,这通常是不好的做法,我将在第二秒告诉您为什么它起作用。

for (int o = 0; o < array.Element[i].Object.length; ++o)
{
    if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
    {

Now, with all of that ugly nested loopyness, we've found out that your Item is not null. 现在,在所有这些丑陋的嵌套循环中,我们发现您的Item不为null。 On top of that, you have access to ALL of the potential values here, and can group them as you like. 最重要的是,您可以在此处访问所有潜在值,并可以根据需要对其进行分组。 Here's how I would put the whole thing together for simplification. 为简化起见,这就是我将整个过程放在一起的方法。

List<string> arrayValues = new List<string>();
if (array != null && array.Element != null)
{
    for (int i = 0; i < array.Element.length; ++i)
    {
        //bool found = false;
        if (array.Element[i] != null && array.Element[i].Object != null)
        {
            for (int o = 0; o < array.Element[i].Object.length; ++o)
            {
                if (array.Element[i].Object[o] != null && !string.IsNullOrEmpty(array.Element[i].Object[o].Item))
                {
                    arrayValues.Add(array.Element[i].Object[o].Item);
                    //if you want to drop out here, you put a boolean in the bottom loop and break and then break out of the bottom loop if true
                    //found = true;
                     //break;
                }
            }
        }
        //if (found)
        //  break;
    }
}
if (arrayValues.Count > 0)
{
    //do stuff with arrayValues
}

Could you do something like: 你能做点什么:

if(array.Element[0] != null || array.Element[1] != null){
    //execute code
}

Your code is probably subject to refactor. 您的代码可能需要重构。

I assume it can work this way: 我认为它可以这样工作:

var obj = array.Element.FirstOrDefault(x => x.Object.Length > 0);
if (obj != null)
{
  if (obj.Object[0].Item.Length != 0) 
  {
    // do whatever is necessary
  }
}

Place both tests together using the short-circuit && so that the second test doesn't occur if the first fails: 使用短路&&将两个测试放在一起,这样,如果第一个测试失败,则第二个测试不会发生:

object element0 = array.Element[0].Object;
object element1 = array.Element[1].Object;

// Ensure at least one Object array has a non-empty value.
if ((element0.Length > 0 && !string.IsNullOrEmpty((string)element0.Object[0].Item))
    || (element1.Length > 0 && !string.IsNullOrEmpty((string)element1.Object[1].Item)))
{
    // ...
}

I am presuming it is Object[1] causing the exception--you weren't clear on that. 我猜想是由Object[1]引起异常的-您对此还不清楚。 If it is Element[1] that causes the exception (or both), then you need to pre-test the length of the array: 如果是Element[1]导致异常(或两者),则需要预先测试数组的长度:

if ((array.Element[0].Length != 0 && HasValue(array.Element[0].Object))
    || (array.Element[1].Length > 1 && HasValue(array.Element[1].Object)))
{
    // ...
}

// <summary>
// Returns true if the specified string array contains a non-empty value at
// the specified index.
// </summary>
private bool HasValue(System.Array array, int index)
{
    return array.Length > index && 
        !string.IsNullOrEmpty((string)array.Object[index].Item);
}

I think you can put your check in right before your first if Check. 我认为您可以将支票放在您的第一笔支票之前。

if (array.Length > 1 && array.Element[0].Object.Length > 0 || array.Element[1].Object.Length > 0) //making sure there's at least one Object array that has values
 {                
    if (array.Element[0].Object[0].Item.Length != 0 || array.Element[1].Object[0].Item.Length != 0) //this is where I check that at least one of the Items (strings) is not empty
       {
           // execute code here
       }
 }

This should just short-circuit out if your array doesn't have both Elements. 如果您的数组没有两个元素,则应该将其短路。

for (long i = 0; i <= (output3.Length); i++)
{
    output1.WriteByte(output3[i]); -----> index out of range exception correct it
    output1.WriteByte(output3rx[i]);
}

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

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