【问题标题】:Why is this false if statement running? (C#)为什么这个错误的 if 语句正在运行? (C#)
【发布时间】:2016-09-08 03:33:48
【问题描述】:

查看链接:

http://i.imgur.com/gFcamd8.png

注意底部的 Autos 窗口显示 toParse = ""。但是 toParse != "" 无论如何都会评估为 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);
        }
    }

【问题讨论】:

  • toParse 的值是多少?
  • toParse的长度是多少?
  • 见操作:toParse = ""
  • 长度为 0。如果我使用 toParse.Length != 0,也会出现同样的问题。

标签: c# if-statement logical-operators


【解决方案1】:

仅给出这一个快照时,很难看到调试会话期间发生的所有事情。但是,由于 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 关键字的更多信息,请参阅 this StackOverflow issuethis official Microsoft documentation

我希望这会有所帮助!

【讨论】:

    【解决方案2】:

    在图像中,这一行newNode.parseString(inside) 被突出显示,这意味着它在调用堆栈中并且在崩溃之前被调用。该行可能会将 toParse 更改为“”。

    【讨论】:

    • 我已经修改了我的 OP 以显示整个方法。调用 parseString() 时我首先检查的是传递的字符串是否为 == ""。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2021-12-03
    • 1970-01-01
    • 2021-01-14
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多