我使用以下代码拆分字符串并存储它:
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] 存在,有时不存在。
我该如何解决这个问题?
最佳答案
只需检查 if 语句中返回的数组的长度
if( proxyAdrs.Length > 2 && proxyAdrs[2] != null)
{
item.Username = proxyAdrs[2];
}
你得到异常的原因是拆分返回的数组大小小于你正在访问的索引。如果您要访问数组元素 2
,则数组中必须至少有 3
元素,因为数组索引以 0
关于c# - 拆分 - 索引超出数组范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13581182/