数组未正确初始化,所有记录均为null.c#

本文关键字:记录 null 初始化 数组 | 更新日期: 2024-10-22 05:23:33

我有多个文本文件正在读取字符串数组。根据用户按下的按钮,富文本框中会填充来自数组中某个字符串的文本。

这是正在设置的数组的代码。请注意,还有更多if/else语句在做相同的事情,但使用不同的文件,但我不想在这里浪费空间,把它们也扔进去。

  namespace ModNote
  {
public class backgroundProgram
{
    public static int moduleNumber;
    public static string[] noteArray;
    public static string[] moduleArray = new string[7];
    const string dataPath = @"Data'";
    const string gamesPath = "CGP1005M.txt";
    const string algorithmsPath = "CMP1124M.txt";
    const string programmingPath = "CMP1127M.txt";
    const string operatingPath = "CMP1005M.txt";
    const string computerPath = "CMP1125M.txt";
    const string webPath = "CMP1129M.txt";
    const string informationPath = "CMP1123M.txt";

    public backgroundProgram()
    {
        #region // Reading to the array
        // Check the month file exists?
        if (File.Exists(dataPath + gamesPath))
        {
            // Read in the month file.
            moduleArray[0] = File.ReadAllText(dataPath + gamesPath);
        }
        else
    }
}

不幸的是,数组在赋值时为null,所以我在上面的代码中放了一个断点,而这些行永远不会被执行,我哪里错了?

请注意,根据用户在程序开始时单击的按钮,"backgroundProgram.moduleNumber"的值将发生变化。

 namespace ModNote
 {
public partial class moduleinfoScreen : Form
{
    public moduleinfoScreen()
    {
        InitializeComponent();
        Shown += moduleinfoScreen_Shown;
    }
    public void moduleinfoScreen_Shown(Object sender, EventArgs e)
    {
        switch (backgroundProgram.moduleNumber)
        {
            case 1:
                moduleinfoTextbox.Text = backgroundProgram.moduleArray[0];
                break;
            case 2:
                moduleinfoTextbox.Text = backgroundProgram.moduleArray[0];
                break;
            case 3:
                moduleinfoTextbox.Text = backgroundProgram.moduleArray[0];
                break;
            case 4:
                moduleinfoTextbox.Text = backgroundProgram.moduleArray[0];
                break;
            case 5:
                moduleinfoTextbox.Text = backgroundProgram.moduleArray[0];
                break;
            case 6:
                moduleinfoTextbox.Text = backgroundProgram.moduleArray[0];
                break;
            case 7:
                moduleinfoTextbox.Text = backgroundProgram.moduleArray[0];
                break;
            default:
                MessageBox.Show("Nope");
                break;
        }
    }

你知道为什么我的数组代码没有被执行吗?

数组未正确初始化,所有记录均为null.c#

问题最有可能出现在以下行:

                if (File.Exists(dataPath + gamesPath))

这是在查找Data''CGP1005M.txt中的文件。因为没有起始斜杠,它将在当前路径中查找文件。运行c#程序时,当前路径将是bin文件夹。

例如,如果您正在运行的项目位于c:''project,它将尝试在c:''project''bin''debug''data''CGP105M.txt.中查找文件

考虑到你项目的位置,这些路径正确吗?