拆分-索引超出了数组的范围 [英] Split - Index was outside the bounds of the array

查看:111
本文介绍了拆分-索引超出了数组的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码拆分字符串并将其存储:

Im using the following code to split up a string and store it:

string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);


if(proxyAdrs[2] != null)
{
    item.Username = proxyAdrs[2];
}

if (proxyAdrs[3] != null)
{
    item.Password = proxyAdrs[3];
}

问题是我正在获得


索引在数组的边界之外。

Index was outside the bounds of the array.

proxyAdrs [2] 不存在。

有时proxyAdrs [2]有时不存在。

Sometimes proxyAdrs[2] will be there sometimes not.

我该如何解决?

推荐答案

只需检查if语句中返回的数组的长度

Just check the length of the array returned in your if statement

if( proxyAdrs.Length > 2 &&  proxyAdrs[2] != null)
    {
        item.Username = proxyAdrs[2];
    }

出现异常的原因是拆分返回的数组大小小于您正在访问的索引。如果要访问数组元素 2 ,则数组中必须至少有 3 个元素,因为数组索引以 0

The reason you are getting the exception is that the split is returning array of size less than the index you are accessing with. If you are accessing the array element 2 then there must be atleast 3 elements in the array as array index starts with 0

这篇关于拆分-索引超出了数组的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆