質問

I am new to c# programming. Could someone please help me find out how to add a second test to this code :

if (item.CalcInsor_Desc != null)
   {
        string[] CalcInsor_Desc = item.CalcInsor_Desc.ToString().Split('.');
        schema2.CalcInsonorisation_TypeCode = CalcInsor_Desc[0];
        schema2.CalcInsonorisation_Desc = CalcInsor_Desc[1];
   }

It ruturn an exception "System.IndexOutOfRangeException: Index was outside the bounds of the array. "in the case CalcInsonorisation_Desc is null.

役に立ちましたか?

解決

You can try

if (item.CalcInsor_Desc != null)
{
    string[] CalcInsor_Desc = item.CalcInsor_Desc.ToString().Split('.');
        if (CalcInsor_Desc.Length >= 2)
        {
             schema2.CalcInsonorisation_TypeCode = CalcInsor_Desc[0];
             schema2.CalcInsonorisation_Desc = CalcInsor_Desc[1];
        }
}

他のヒント

if (!item.CalcInsor_Desc.Equals(null))
   {
        string[] CalcInsor_Desc = item.CalcInsor_Desc.ToString().Split('.');
        if(CalcInsor_Desc.Length >= 2){
            schema2.CalcInsonorisation_TypeCode = CalcInsor_Desc[0];
            schema2.CalcInsonorisation_Desc = CalcInsor_Desc[1];
        }
   }

Check the array contains minimum required elements

if(CalcInsor_Desc.Length>1)
{
 schema2.CalcInsonorisation_TypeCode = CalcInsor_Desc[0];
 schema2.CalcInsonorisation_Desc = CalcInsor_Desc[1];
}

Or

  if(CalcInsor_Desc.Length=1)
    {
     schema2.CalcInsonorisation_TypeCode = CalcInsor_Desc[0];
     schema2.CalcInsonorisation_Desc = string.Empty;
    }
  if(CalcInsor_Desc.Length>1)
    {
     schema2.CalcInsonorisation_TypeCode = CalcInsor_Desc[0];
     schema2.CalcInsonorisation_Desc = CalcInsor_Desc[1];
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top