C# 此代码导致意外结果
我有一个对象声明为:C# 此代码导致意外结果,c#,c#-2.0,c#-to-vb.net,C#,C# 2.0,C# To Vb.net,我有一个对象声明为: private string SourceProgram; 基本上,我尝试使用下面的代码解析一些东西: private void LabelScan(System.IO.BinaryWriter OutputFile, bool IsLabelScan) { if (char.IsLetter(SourceProgram[CurrentNdx])) { if (IsLabel
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}
而currentdx
的值是46
出了什么问题。字符串变量SourceProgram
是否为长度<46
如果是,如何修复此代码?代码似乎在字符串源程序中查找新行字符。可能SourceProgram不包含\n 当然,最好使用
int position=SourceProgram.indexOf(“\n”)
来查找
此外,在这段代码中,您似乎没有将CurrentNdx重置为零,这在其他地方可能是必需的
while (SourceProgram[CurrentNdx] != '\n')
CurrentNdx++;
可能您的SourceProgram字符串不包含换行符,或者在CurrentNdx超出字符串中的任何换行符后调用该函数。是,此错误表明SourceProgram少于47个字符。这就是我们所能告诉您的,但不必查看SourceProgram的内容。在哪里重置
CurrentNdx
?是的-字符串似乎少于47个字符。“字符串变量是否<46?”这一问题不应该是您应该能够在调试器中看到的吗?@Lasse V.Karlsen::显然它超出了范围@BrokenGlass::我无法重置CurrentNdx,因为我用它来读取文件,它需要不断递增。@用户:好的-那么你在哪里添加到字符串?如果是固定字符串,请检查下面的答案-您可能没有\n
是否有办法使SourceProgram变大。。。我是说动态?@user667389那么为什么不使用这个indexOf指定要从中搜索的第一个字符呢。那么这可以用来更新CurrentNdx吗?