尝试捕捉 - 好习惯?运行时的用户输入



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

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;

相关内容

最新更新