2012-04-11 24 views
7

voglio scrivere un assegno per alcune condizioni, senza dover utilizzare try/catch e voglio evitare la possibilità di ottenere Indice Fuori errori di intervalloPrevenire Indice fuori del campo Errore di

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 
     } 
} 

Quindi il problema che ho sto di fronte è che nel secondo controllo ho bisogno di vedere se ho un articolo che non è vuoto. Tuttavia, se non si dispone di Element[1], ottengo l'eccezione Indice fuori intervallo. Il problema è che potrebbero esserci 2 elementi e uno (o entrambi) potrebbero avere matrici di oggetti vuote. Il codice dovrà essere eseguito solo se una delle stringhe Item non è vuota.

Spero di averlo spiegato bene. Come faccio ad evitare di ottenere quell'eccezione in qualsiasi condizione?

+2

perché non utilizzare un '' lista invece di un array? –

+1

Le due condizioni nella prima riga sono uguali, presumibilmente non è intenzionale? –

+0

Mi scuso, ci dovrebbero essere due condizioni diverse, l'ho cambiato. – Victor

risposta

3

OK, è necessario un po 'meglio null checking e un altro codice più cauto qui.

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 
    } 
} 

non è accettabile.

In primo luogo, andiamo controllo nullo

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

per semplicità, si potrebbe usare &&

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

allora, dentro che se, usiamo un ciclo for (since you're stuck on arrays) e Null controllare

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

quindi, poiché si hanno array annidati, si esegue il ciclo ancora. Questo è chiamato nested loop, ed è generalmente una cattiva pratica, ti mostrerò perché funziona in un secondo.

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)) 
    { 

Ora, con tutto quel brutto annidamento, abbiamo scoperto che il tuo articolo non è nullo. Inoltre, puoi accedere a TUTTI i valori potenziali qui e raggrupparli a tuo piacimento. Ecco come metterei il tutto insieme per semplificazione.

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 
} 
+1

Ben fatto! Quando comincio ad avere bisogno di codice come questo è quando comincio a pensare se il mio progetto è corretto in primo luogo. Sospetto che il progetto dell'OP possa beneficiare di alcuni cambiamenti fondamentali. –

0

si potrebbe fare qualcosa di simile:

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

Penso che otterrebbe comunque quell'eccezione se 'Element [1]' non esiste. – Victor

+0

Ah, credo che tu abbia ragione. – Ryan

0

Il codice è probabilmente soggetto a refactoring.

presumo può funzionare in questo modo:

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

Luogo entrambi i test insieme con il corto-circuito && modo che il secondo test non si verifica se il primo fallisce:

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))) 
{ 
    // ... 
} 

Presumo che sia l'Object[1] a causare l'eccezione - non eri chiaro su questo. Se è Element[1] che causa l'eccezione (o entrambi), allora avete bisogno di pre-test la lunghezza dell'array:

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); 
} 
0

penso che si può mettere il check-in a destra prima della prima, se 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 
     } 
} 

Questo dovrebbe solo cortocircuitare se l'array non ha entrambi gli elementi.

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

"L'errore di indicizzazione fuori intervallo lo corregge". Er, stava chiedendo a _how_ di farlo. –

Problemi correlati