繁体   English   中英

数组IndexOutOfRange

[英]Array IndexOutOfRange

        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;

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

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

只需使用temp.Length检查:

if (temp.Length > 0)
{
    ...
}

...或使用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;
}

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

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);

另一种方法是使用ElementAtOrDefault

    string[] temp = textBox1.Text.Select(c => c.ToString());
    string temp2 = "" + temp.ElementAtOrDefault(0);
    string temp3 = "" + temp.ElementAtOrDefault(1);
    string temp4 = "" + temp.ElementAtOrDefault(2);
    textBox2.Text = temp2;
    textBox3.Text = temp3;
    textBox3.Text = temp4;

解决此类问题的一般方法是在访问源值(数组,字符串或向量)之前检查其值。 例如:

string  temp = textBox1.Text;

if (temp.Length > 0)
    textBox2.Text = temp.Substring(0, 1);
if (temp.Length > 1)
    textBox3.Text = temp.Substring(1, 1);
if (temp.Length > 2)
    textBox4.Text = temp.Substring(2, 1);

如果大小是固定的,即没有。 字符的长度是3或长度是3,则它必须像...

string temp = textBox1.Text; char[] array1 = temp.ToCharArray(); if(temp.length==3) { string temp2 = "" + array1[0]; string temp3 = "" + array1[1]; string temp4 = "" + array1[2]; textBox2.Text = temp2;
textBox3.Text = temp3; textBox3.Text = temp4; }
string temp = textBox1.Text; char[] array1 = temp.ToCharArray(); if(temp.length==3) { string temp2 = "" + array1[0]; string temp3 = "" + array1[1]; string temp4 = "" + array1[2]; textBox2.Text = temp2;
textBox3.Text = temp3; textBox3.Text = temp4; }
这将是工作,如果乌拉圭回合的字符串长度为3 ....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM