【发布时间】:2014-12-11 05:57:14
【问题描述】:
这里的代码显示了我用来向用户打印文本输出的“打字机效果”。基本上它打印出带有打字机效果的文本。但它会抛出一个错误:
“索引和长度必须引用字符串中的某个位置”
这是我的代码:
private void TypeWriterTimer_Tick(object sender, EventArgs e)
{
const int MaxRetries = 5;
for (int i = 0; i < MaxRetries; i++)
{
try
{
Action final = () => dialogBox.Text = typeWriterReply.Substring(0, TypeWriter_index_Num) + "_";//Substring is a part of Type_Text String that we declared at the start
dialogBox.Dispatcher.Invoke(final, null);
TypeWriter_index_Num++;//Doing a post fix
if (TypeWriter_index_Num == typeWriterReply.Length +1)//An if statment with a condition of course
{
TypeWriter_index_Num = 0;
TypeWriterTimer.Stop();
}
dialogBox.Focus();
dialogBox.CaretIndex = dialogBox.Text.Length;
dialogBox.ScrollToEnd();
break;
}
catch (Exception tw)
{
MessageBoxResult result = MessageBox.Show("Type Writer ERROR");
Console.WriteLine(tw.ToString());
}
}
}
TypeWriterReply 是正在打印的文本,所有变量都是全局声明的。
为什么会抛出这个错误?
【问题讨论】:
-
表达式“TypeWriter_index_Num == typeWriterReply.Length +1”当然是一个错误,如果不是你要问的那个。字符串中唯一有效的索引是 小于 typeWriterReply.Length 的值。你阻止一个角色太晚了。
-
请不要这样编码:
catch (Exception tw)。像这样捕获所有异常是一种不好的做法。
标签: c# wpf loops timer error-handling