此代码的意外结果
我有一个对象声明为:
private string SourceProgram;
基本上我正在尝试使用下面的代码解析一些内容:
private void LabelScan(System.IO.BinaryWriter OutputFile, bool IsLabelScan)
{
if (char.IsLetter(SourceProgram[CurrentNdx]))
{
if (IsLabelScan) LabelTable.Add(GetLabelName(), AsLength);
while (SourceProgram[CurrentNdx] != '\n')
CurrentNdx++;
CurrentNdx++;
return;
}
EatWhiteSpaces();
ReadMneumonic(OutputFile, IsLabelScan);
}
但是我在执行时遇到错误:
- SourceProgram[CurrentNdx]
'SourceProgram[CurrentNdx]' threw an exception of
type 'System.IndexOutOfRangeException' char {System.IndexOutOfRangeException}
- base {"Index was outside the bounds of the array."}
System.SystemException {System.IndexOutOfRangeException}
并且 CurrentNdx
的值是 46。
出了什么问题。是 SourceProgram
的字符串变量 length
46 ?
如果是,如何修复此代码?
I have an object declared as:
private string SourceProgram;
Basically i am trying to parse some stuff using the code below:
private void LabelScan(System.IO.BinaryWriter OutputFile, bool IsLabelScan)
{
if (char.IsLetter(SourceProgram[CurrentNdx]))
{
if (IsLabelScan) LabelTable.Add(GetLabelName(), AsLength);
while (SourceProgram[CurrentNdx] != '\n')
CurrentNdx++;
CurrentNdx++;
return;
}
EatWhiteSpaces();
ReadMneumonic(OutputFile, IsLabelScan);
}
However i get an error on execution:
- SourceProgram[CurrentNdx]
'SourceProgram[CurrentNdx]' threw an exception of
type 'System.IndexOutOfRangeException' char {System.IndexOutOfRangeException}
- base {"Index was outside the bounds of the array."}
System.SystemException {System.IndexOutOfRangeException}
And the Value of CurrentNdx
is 46.
What has gone wrong. Is the string variable SourceProgram
of length < 46
?
If yes, how to fix this code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,此错误表明 SourceProgram 少于 47 个字符。虽然没有看到 SourceProgram 的内容,但我们能告诉您的几乎就是这些。
Yes, this error suggests that SourceProgram has less than 47 characters. That's pretty much all we can tell you though without seeing the contents of SourceProgram.
该代码似乎在字符串 SourceProgram 中查找换行符。也许 SourceProgram 不包含 \n?
当然,最好使用 intposition = SourceProgram.indexOf("\n") 来查找 \n 的位置
此外,在此代码中您似乎没有将 CurrentNdx 重置为零,这可能在其他地方需要
The code seems to look for a new line character in the string SourceProgram. Maybe SourceProgram doesn't contain a \n?
Surely it would be better to use
int position = SourceProgram.indexOf("\n")
to find the position of the \nAlso, you don't appear to be resetting CurrentNdx to zero in this code, which would likely be required elsewhere
也许您的 SourceProgram 字符串不包含换行符,或者在 CurrentNdx 超出字符串中的任何换行符之后调用该函数。
maybe your SourceProgram string doesn't contain a newline, or the function is called after CurrentNdx is beyond any newlines in the string.