由于未知原因在C#中使用字符串数组时,会出现多个运行时异常

问题描述 投票:0回答:1

我正在为一种编程语言编写词法分析器或标记器。主要功能之一是将源代码行拆分为“令牌”。我通过分割空格来创建字符串数组来实现这一点。因此,当我要保留字符串时,必须在分割行时临时将内容更改为关键字,然后再将字符串放回去。直到我为该语言开发了变量系统,并且必须保留多个字符串,这才起作用。然后所有异常地狱都松开了。

例外:

NullReferenceException(第12行)subStringArg[ini] = quotes[1];

IndexOutOfRangeException(第34行)value = value.Replace("STRING", subStringArg[ini]);

最小可复制示例:

public static string[] LexLine(string line)
        {
            string[] subStringArg = null;
            string[] quotes = null;
            string[] tokens = null;
            int ini = 0; // Random name
            while (line.Contains('\"'))
            {
                if (line.Contains('\"'))
                {
                    quotes = line.Split('\"');
                    subStringArg[ini] = quotes[1];
                }

                if (subStringArg != null)
                {
                    line = line.Replace(quotes[1], "STRING");
                    line = line.Replace("\\", "");
                    line = line.Replace("\"", "");
                }
                ini++;
            }
            tokens = line.Split(' ');
            if (tokens[0] == "Output" && tokens[1] != "STRING")
            {
                tokens[1] = IO.OutputVariable(tokens[1]);
            }
            ini = 0;
            foreach (string i in tokens)
            {
                if (i == "STRING" && subStringArg != null && verificitate == 1)
                {
                    string value = i;
                    value = value.Replace("STRING", subStringArg[ini]);
                    tokens[currentArrayEntry] = value;
                }
                currentArrayEntry++;
                ini++;
            }
            return tokens;
        }

源代码(来自我的语言):

Output "Defining variables..." to Console. // Exception thrown here
New string of name "sampleStringVar" with value "sample".
Output "enter your name:" to Console.
Get input.
Output sampleStringVar to Console.

我在这里问是因为我不知所措。我不应该从assigning值中获取NullReferenceException。

c# nullreferenceexception lexer indexoutofrangeexception
1个回答
0
投票

您设置了以下内容

string[] subStringArg = null;

然后您再执行此操作

subStringArg[ini] = quotes[1];

但是您尚未初始化subStringArg,因此它仍然为空,因此您无法为其分配任何内容,您将获得NullReferenceError

您必须先初始化数组,然后才能向其中分配任何内容。

[此外,您不应该先检查quotes[1]就拥有一个值。这将导致IndexOutOfRangeException

另外一点。 while循环内的第一个If语句将检查与while循环相同的条件,因此也将成立!

所以以下内容会更好

string[] subStringArg = new String[enterKnownLengthHere_OrUseALIst];
...
 while (line.Contains('\"'))
 {
        quotes = line.Split('\"');
        if(quotes != null && quotes.Length >= 2)
            subStringArg[ini] = quotes[1];
        else
           //Error handling here!


        if (subStringArg.Length >= 1)
        {
                line = line.Replace(quotes[1], "STRING");
                line = line.Replace("\\", "");
                line = line.Replace("\"", "");
        }
        ini++;
    }
© www.soinside.com 2019 - 2024. All rights reserved.