将文本添加到String时的IndexOutOfRangeException

时间:2014-12-16 01:27:54

标签: c# arrays string

我的程序使用while循环将两个数组添加到字符串的一部分中 例如:

hnames[0] = user
hvals[0] = admin

转换为:user = admin&

我收到IndexOutOfRangeException并且我不知道如何修复它。

string[] hnames = names.ToArray(typeof(string)) as string[];
string[] hvals = values.ToArray(typeof(string)) as string[];
String postData = "";
//Loops through the arrays and put data into postData var
while (i < hnames.Length)
{
    i++;
    int end = hnames.Length;
    end--;
    if (!(i == end))
    {
        postData = postData + hnames[i] + "=" + hvals[i] + "&"; //IndexOutOfRangeException here
    }
    else
    {
        postData = postData + hnames[i] + "=" + hvals[i];
    }
}

2 个答案:

答案 0 :(得分:2)

您在使用之前递增i,因此在循环结束时,i = hnames.Length - 1时,循环开始时的i++;设置为i = hnames.Length },这是在数组的末尾。您实际上也在跳过i = 0

i++;向下移动到循环的末尾。

答案 1 :(得分:0)

我只想按照其他人的建议,使用foreach向您展示逻辑的简化版本。行数可能相同,但我认为这很容易阅读。

        string[] hnames = names.ToArray(typeof(string)) as string[];
        string[] hvals = values.ToArray(typeof(string)) as string[];

        string postData = string.Empty;
        bool isFirst = true;
        int i = 0;

        /* Assumption - Both arrays hnames and hvals are of same length.
                        Otherwise you'll get the same error if hvals.Length < hnames.Length even if you use the foreach
         */
        foreach (string hname in hnames)
        {
            if (isFirst)
            {
                postData = hname + "=" + hvals[i] + "&"; //IndexOutOfRangeException here
                isFirst = false;
            }
            else
            {
                postData += hname + "=" + hvals[i];
            }

            i++;
        }