gpt4 book ai didi

c# - 拆分 - 索引超出数组范围

转载 作者:太空狗 更新时间:2023-10-29 21:09:42 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com