数组IndexOutOfRange

Squ*_*nge 0 c# arrays indexoutofboundsexception

        string temp = textBox1.Text;
        char[] array1 = temp.ToCharArray();
        string temp2 = "" + array1[0];
        string temp3 = "" + array1[1];
        string temp4 = "" + array1[2];
        textBox2.Text = temp2;
        textBox3.Text = temp3;
        textBox4.Text = temp4;
Run Code Online (Sandbox Code Playgroud)

当用户在textBox1中输入少于三个字母时,如何防止发生IndexOutOfRange错误?

Jon*_*eet 10

如果用户只在textBox1中输入少于三个字母,我将如何阻止IndexOutOfRange错误?

只需检查使用temp.Length:

if (temp.Length > 0)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

...或使用switch/ case.

此外,您根本不需要阵列.只需调用ToString每个角色,或使用Substring:

string temp = textBox1.Text;
switch (temp.Length)
{
    case 0:
        textBox2.Text = "";
        textBox3.Text = "";
        textBox4.Text = "";
        break;
    case 1:
        // Via the indexer...
        textBox2.Text = temp[0].ToString();
        textBox3.Text = "";
        textBox4.Text = "";
        break;
    case 2:
        // Via Substring
        textBox2.Text = temp.Substring(0, 1);
        textBox3.Text = temp.Substring(1, 1);
        textBox4.Text = "";
        break;
    default:
        textBox2.Text = temp.Substring(0, 1);
        textBox3.Text = temp.Substring(1, 1);
        textBox4.Text = temp.Substring(2, 1);
        break;
}
Run Code Online (Sandbox Code Playgroud)

另一种选择 - 甚至更整洁 - 是使用条件运算符:

string temp = textBox1.Text;
textBox2.Text = temp.Length < 1 ? "" : temp.Substring(0, 1);
textBox3.Text = temp.Length < 2 ? "" : temp.Substring(1, 1);
textBox4.Text = temp.Length < 3 ? "" : temp.Substring(2, 1);
Run Code Online (Sandbox Code Playgroud)