c# - 为什么我需要初始化字符串变量 'name' ?

标签 c#

这个问题很难解决。在输出到列表框的末尾附近的代码行中,我一直在“名称”变量上收到错误“使用未分配的局部变量”。

解决方案是初始化变量“名称”。

起初,我只是简单地声明“名称”变量,而没有对其进行初始化。这引发了“使用未分配的局部变量”的错误。当我最终也初始化那个变量时(如下所示),错误消失了。

但我不明白这一点,因为当代码到达输出行时,名称变量确实被赋值了。

有人可以解释一下为什么初始化“name”变量可以消除编译错误吗?

'''

        try
        {
            StreamReader inputFile;     // StreamReader object to read the file
            string line;                // To hold a line from the file.
            int row = 0;                // Student/line counter.
            int column = 0;             // Counter for columns in CSV file.
            int total = 0;              // Accumulator for grades.
            double average = 0;         // Average test score
            string name = "";           // each student's name

            // Create delimiter array
            // Why is this necessary?  Why not just put the delimiter in the Split method call?
            //char[] delim = { ',' };

            // Open the CSV file
            inputFile = File.OpenText("Grades.csv");

            while (!inputFile.EndOfStream)
            {
                // increment the row counter
                row++;

                // Read a line from the file
                line = inputFile.ReadLine();

                // Get the test scores as tokens
                string[] scores = line.Split(',');

                // Set the accumulator to zero
                total = 0;

                // Calculate the total of the test score tokens
                for (column = 0; column < scores.Length; column++)
                {
                    if (column == 0)
                    {
                        name = scores[column];
                    }
                    else
                    {
                        total += int.Parse(scores[column]);
                    }
                }

                // Calculate the average test score
                average = (double)total / (scores.Length - 1);

                // Display the average
                //averagesListBox.Items.Add("The average for student " + row + " is " + average.ToString("n1"));
                averagesListBox.Items.Add("The average for " + name + " is " + average.ToString("n1"));
            }

            // Close the file
            inputFile.Close();

            // Display the total records read
            totalLabel.Text = row.ToString("n0");
        }

        catch (Exception ex)
        {
            // Display an error message
            MessageBox.Show(ex.Message);
        }
    }

'''

最佳答案

编译器无法证明它确实在任何地方被设置。如果 scores.Length 为零怎么办?然后就没有任务了。因此,编译器在抛出未为其赋值的可能情况的错误时是正确的。

如果您为 scores.Length 添加一个总是大于零的条件,编译器可能能够推断出一个值总是被设置。而且你总是可以直接将它设置为数组中的第一个元素并从 1 开始循环,这样效率更高。

关于c# - 为什么我需要初始化字符串变量 'name' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58901079/

相关文章:

C# 从数组中保存图像

c# - 使用 C# 进行自动化 Flash 测试

c# - Windows Phone 8.1 RT - 保存和加载页面状态

c# - Silverlight Bing 通过 SSL 映射

c# - 如何将多个文件与其他表单字段一起上传,ASP.NET MVC

javascript - 基于选中的复选框启用和禁用两个不同的按钮 - JQuery

c# - CA0001 : Object reference not set to an instance of an object

c# - 从 JSON 字符串反序列化异常

c# - Visual Web 开发人员控制台应用程序,如何

c# - 取消装箱卡住 Winforms ComboBox