为什么这个假if语句在运行?(c#)

本文关键字:运行 语句 if 为什么 | 更新日期: 2023-09-27 18:06:18

查看链接:

https://i.stack.imgur.com/NH6bX.png

注意底部的自动窗口显示toParse = "。然而,无论如何,topparse != "的计算结果都为true,这会导致应用程序崩溃。

下面是完整的方法:

public void parseString(string toParse)
    {
        while (toParse != "")
        {
            string nextLine = readLine(ref toParse);
            if (nextLine.IndexOf("//") == 0)
            {
                comments.Add(nextLine);
                continue;
            }
            if (nextLine.IndexOf(".") == 0)
            {
                string[] declarationParts = nextLine.Split(' ');
                string declarationString = declarationParts[0].Substring(1, declarationParts[0].Length - 1);
                declarationString = char.ToUpper(declarationString[0]) + declarationString.Substring(1);
                DirectiveEnum type = (DirectiveEnum)Enum.Parse(typeof(DirectiveEnum), declarationString);
                string[] attributes = declarationParts.Skip(1).ToArray();
                MSILNode newNode = new MSILNode(type);
                newNode.addAttributes(attributes);
                toParse = toParse.Trim();
                if (toParse != "")
                {
                    while (toParse[0] != '{' && toParse[0] != '.' && toParse.IndexOf("//") != 0)
                    {
                        nextLine = readLine(ref toParse);
                        attributes = nextLine.Split(' ');
                        newNode.addAttributes(attributes);
                    }
                    if (toParse[0] == '{')
                    {
                        readLine(ref toParse);
                        string inside = separate(ref toParse, "}");
                        newNode.parseString(inside);
                    }
                }
                subNodes.Add(newNode);
                continue;
            }
            Console.WriteLine(nextLine);
        }
    }

为什么这个假if语句在运行?(c#)

当只给出这一个快照时,很难看到调试会话期间发生的所有事情。然而,由于toParse是通过对函数readline()的引用传递的(第57行),因此它的值可以在该函数的函数体中更改。

从原始问题中提供的PNG图像:

53 if (toParse != "")
54 {
55     while (toParse[0] != '{' && toParse[0] != '.' && toParse.IndexOf("//") != 0)
56     {
57         nextLine = readLine(ref toParse);
58         ...

第53行,toParse不为空。然后,在while循环的一次迭代期间,它被更新为空值。这将导致任何对数组下标的访问(即while条件中的toParse[0])都会抛出异常。

有关c#中ref关键字的更多信息,请参阅此StackOverflow问题或此微软官方文档。

我希望这对你有帮助!

在图像中,newNode.parseString(inside)行被突出显示,这意味着它在Callstack中并且在崩溃之前被调用。这一行可能会将topparse变成"。