当我尝试使用 IF 语句为变量赋值时出现未赋值变量错误

Use of unassigned variable error when I am trying to assign values to variables using IF statements

我正在 Windows 表单中编写一个程序,我试图使用 IF 语句为变量赋值,具体取决于单击表单中的哪些单选按钮。我在下面的粗体行中收到错误“使用未分配的变量”。问题是 TotalWeeks 显然没有被分配,但是我在上面的 IF 语句中为它分配了一个值。任何人都可以提出可能的修复或想法来尝试解决问题吗?

private void button1_Click(object sender, EventArgs e)
{
    //Assigning variables
    int WeeklyRate; //To assign integer values for "WeeklyRate" for future calculation use. If Radio button clicked it has value of radio button etc. 
    if (radioButton1.Checked)
    {
        WeeklyRate = 10;
    }
    else if (radioButton2.Checked)
    {
        WeeklyRate = 15;
    }
    else if (radioButton3.Checked)
    {
        WeeklyRate = 20;
    }

    int TotalWeeks;//assign values to total weeks based on number of months selected, to use in calculations for total cost.
    if (radioButton4.Checked)
    {
        TotalWeeks = 12;
    }
    else if (radioButton5.Checked)
    {
        TotalWeeks = 52;
    }
    else if (radioButton6.Checked)
    {
        TotalWeeks = 104;
    }

    int Payments;//assigning the amount of payments based on frequency radiobutton selected. 
    if (radioButton7.Checked)
    {
        **Payments = TotalWeeks;**
    }
    else if (radioButton8.Checked)
    {
        **Payments = TotalWeeks / 4;**
    }
}
}
}

radioButton4radioButton5radioButton6 都没有被选中时,例如不能除以 4。

你应该在初始化变量时使用它

int TotalWeeks = 0;

(结果:如果不选中单选按钮,Payments 将为 0)


或者初始化时这样

int? TotalWeeks = null;

以及分配付款金额时的这个

if (radioButton7.Checked && TotalWeeks is not null)
{
    Payments = TotalWeeks;
}
else if (radioButton8.Checked && TotalWeeks is not null)
{
    Payments = TotalWeeks / 4;
}

(结果:现在 Payments 变量未分配,当未选中单选按钮时)

编辑:谢谢 GSerg,我在 int 之后忘记了 ? 使其可为空