C# 试着抓住好习惯?运行时的用户输入

C# 试着抓住好习惯?运行时的用户输入,c#,if-statement,try-catch,user-input,textchanged,C#,If Statement,Try Catch,User Input,Textchanged,这个问题建立在我4天前提出的问题之上。为了避免出现System.ArgumentOutOfRangeException问题,我做了很多尝试。出现此问题的原因是if语句位于文本更改事件中,并检查了运行时出现的8个字符。因此,并非所有字符都是立即可用的,而是由用户的输入动态生成的。这就是问题开始的地方,每当文本框中的文本发生更改时,就会触发事件,同时,程序立即需要8个字符,并在逻辑上给出错误消息System.ArgumentOutOfRangeException。为了解决这个问题,我在try-cat

这个问题建立在我4天前提出的问题之上。为了避免出现System.ArgumentOutOfRangeException问题,我做了很多尝试。出现此问题的原因是if语句位于文本更改事件中,并检查了运行时出现的8个字符。因此,并非所有字符都是立即可用的,而是由用户的输入动态生成的。这就是问题开始的地方,每当文本框中的文本发生更改时,就会触发事件,同时,程序立即需要8个字符,并在逻辑上给出错误消息System.ArgumentOutOfRangeException。为了解决这个问题,我在try-catch块中添加了hole-if语句。现在它起作用了,但这是一个好的做法吗?是否有其他/更好的解决方案?以下是我的代码摘录:

private void txtBoxEingabe_TextChanged(object sender, EventArgs e)
{
    axAcroPDF1.LoadFile("DONTEXISTS.pdf");

    radioButton1.Visible = false;
    radioButton2.Visible = false;

    string text = txtBoxEingabe.Text.Substring(0, txtBoxEingabe.TextLength);

    try
    {
        if (text.Substring(0, 3) == "SEH" && text.Substring(3, 1) == "M" && Convert.ToInt32(text.Substring(4, 4)) <= 2999 && (text.Substring(8, 1) == "H" || text.Substring(8, 1) == "R"))
        {
            radioButton1.Visible = true;
            radioButton2.Visible = true;

            radioButton1.Text = "1. Document";
            radioButton2.Text = "2. Document";

            this.radioButton1.CheckedChanged += RadioBtnChangedDC1;
            this.radioButton2.CheckedChanged += RadioBtnChangedDC1;
        }
    }
    catch 
    {

    }

private void RadioBtnChangedDC1(object sender, EventArgs e)
{
    if (radioButton1.Checked == true)
    {
        axAcroPDF1.LoadFile("C:\Doc1.pdf");
        axAcroPDF1.gotoFirstPage();
        Screensize = 100;
        axAcroPDF1.setZoom(Screensize);
        axAcroPDF1.setShowScrollbars(true);
        axAcroPDF1.setShowToolbar(false);
    }
    else if (radioButton2.Checked == true)
    {
        axAcroPDF1.LoadFile("C:\Doc2.pdf");
        axAcroPDF1.gotoFirstPage();
        Screensize = 100;
        axAcroPDF1.setZoom(Screensize);
        axAcroPDF1.setShowScrollbars(true);
        axAcroPDF1.setShowToolbar(false);
    }
}

此程序应该是一个可以显示数百个文档的查看器。

这是一种不好的做法,因为您没有检查错误,而是依赖异常

相反,这样做,你就不需要在那里试一试了

if (txtBoxEingabe.Text.Length < 8)
    return;

为什么不在运行总是会导致异常的代码之前检查长度呢?这是一种好的做法吗?不,不是。应该通过检查来防止预期的错误。盲目捕捉总是一个可怕的想法,因为它会让你对问题视而不见。。