C#:布尔数组在执行期间不更新

C# : bool array is not updating during execution

我有这个示例代码,它基本上从 csv 文件中读取一些字符串数据并更新文本框和一些变量。

csv 文件的格式为 10,0,20,0,0,30,0..etc,包含 20 个值。这个想法是,如果 csv 文件中的任何值是 0,则 isCashAvailable 变量应设置为 false,反之亦然。下面是我的代码。

int[] cash = new int[20];
bool[] isCashAvailable = new bool[20];

public void UpdateCash()
{
        var cashCSV = File.ReadAllText("cash.csv");
        List<string> cashVal = cashCSV.Split(',').ToList();
        
        for (int i = 1; i <= 20; i++)
           {
            var control = this.Controls.Find("textBox" + i.ToString(), true).FirstOrDefault() as TextBox;
            if (cashVal[i - 1] != "0")
              {
                 isCashAvailable[i - 1] = true;
                 control.Text = cashVal[i - 1];
                 cash[i - 1] = int.Parse(cashVal[i - 1]);
              }
                            
            else
              {
                 isCashAvailable[i - 1] = false;
                 control.Text = cashVal[i - 1];
                 cash[i - 1] = int.Parse(cashVal[i - 1]);
                 
              }
           }
}

现在的问题是,当我尝试在运行时更新 isCashAvailablecash 的值时,它没有更新。而如果我通过遍历每次迭代来调试它,它的更新。似乎无法找到发生这种情况的原因。

试试这个:

int[] cash = new int[20];
bool[] isCashAvailable = new bool[20];

var cashCSV = File.ReadAllText("cash.csv");
List<string> cashVal = cashCSV.Split(',').ToList();

// changing this allows you to use i+1 just once, instead of doing i-1 over and over
for (int i = 0; i < 20; i++)
   {
    // this way it will throw an error if TextBox is not found instead of
    // not throwing it here and then throwing NullReference later
    var control = this.Controls.Find("textBox" + (i+1).ToString(), true).First() as TextBox;
    
    //if-else is not needed here
    //TryParse to make sure it always works
    int.TryParse(cashVal[i], out cash[i]);
    isCashAvailable[i] = (cash[i] > 0);
    control.Text = cashVal[i];

    //it works
    Debug.Print($"{i}: isCashAvailable = {isCashAvailable[i]}, cashVal = {cashVal[i]}");
   }