在不超出数组边界的情况下获取 IndexOutOfRangeException

Getting IndexOutOfRangeException without going out of the bounds of the array

所以我有下面的代码使用 orgTxtrndTxt 创建加密字符串,当我调试 Visual Studio 中的代码时,我在第二个 for循环。

我用断点检查了索引的值,它似乎完全在范围内,有人知道问题出在哪里吗? 如果需要更多信息来帮助解决此错误,请给我留言。

//variables
    string scrtTxt = null;
    string rndTxt = null;
    string orgTxt = reader.ReadToEnd();

//assigning random a string from key (set of all capital letters) to rndTxt
for (int i = 0; i < fileInfo.Length; i++) 
        {
             rndTxt += key[random.Next(0, key.Length)]; 
        }

//generating the encrypted message scrtTxt
 int j = 0;
 for (int i = 0; i < fileInfo.Length; i++)
       {
            if ((orgTxt[i] + rndTxt[j] - 'A') <= 'Z' && (orgTxt[i] + rndTxt[j] - 'A') >= 'A')
                    scrtTxt += Convert.ToChar((orgTxt[i] + rndTxt[j] - 'A'));

            if ((orgTxt[i] + rndTxt[j] - 'A') > 'Z')
                    scrtTxt += (char)(scrtTxt[i] - 'Z' + 'A' - 1);//IndexOutOfRangeException error here

            j = j + 1 == rndTxt.Length ? 0 : j + 1;
       }

您正在读取这行代码中的 scrtTxt 数组。

scrtTxt += (char)(scrtTxt[i] - 'Z' + 'A' - 1);

这是您想做的还是应该是 orgTxt 或 rndTxt?