C#中的局部变量
本文关键字:局部变量 | 更新日期: 2023-09-27 18:22:17
来自本地变量的C#错误。我得到错误"使用未分配的本地变量‘CostPerFoot’"
if (decimal.TryParse(txtFeet.Text, out Feet))
{
//Determine cost per foot of wood
if (radPine.Checked)
{
CostPerFoot = PineCost;
}
else if (radOak.Checked)
{
CostPerFoot = OakCost;
}
else if (radCherry.Checked)
{
CostPerFoot = CherryCost;
}
//Calculate and display the cost estimate
CostEstimate = Feet * CostPerFoot;
lblTotal.Text = CostEstimate.ToString("C");
}
特别是最后几行
CostEstimate = Feet * CostPerFoot;
尝试切换变量,但仍然存在问题。
您之所以会出现此错误,是因为编译器认为即使变量CostPerFoot
未初始化,也有可能使用它(这意味着它保持默认值)。使用局部变量不能做到这一点。
您要么必须显式地指定一个默认值,要么确保它在任何情况下都得到一个值。如果使用else
,编译器就不会再抱怨了。
if (decimal.TryParse(txtFeet.Text, out Feet))
{
//Determine cost per foot of wood
if (radPine.Checked)
{
CostPerFoot = PineCost;
}
else if (radOak.Checked)
{
CostPerFoot = OakCost;
}
else if (radCherry.Checked)
{
CostPerFoot = CherryCost;
}
else
{
CostPerFoot = 0;
}
//Calculate and display the cost estimate
CostEstimate = Feet * CostPerFoot;
lblTotal.Text = CostEstimate.ToString("C");
}
如前所述,如果您指定默认值,错误也会消失:
double CostPerFoot = 0;
另一种选择是在else
中抛出异常,如果这种情况不应该发生的话。通过抛出异常来处理无效状态(bug?)是一种很好的做法。这样可以防止您忽略它,并避免错误的值被默默地取下。
事实上,编译器抱怨是因为这一行:
CostEstimate = Feet * CostPerFoot;
因为您的if-else-if
块不包含else
语句,所以可能会使您的CostPerFoot
var值未初始化,因此在上面一行的计算中出现问题。
您遇到的问题:
使用未分配的本地变量
是相当"容易"的。这只是意味着你有一个你使用的变量(在if中,或在某种操作中,…),但在使用它之前,你从来没有给它赋值。
因此,如果您在以下语句中出现以下错误:
CostEstimate = Feet * CostPerFoot;
这意味着,在使用Feet或CostPerFoot之前,它们从未被分配过值(=表示CostEstimate,因此分配仅在计算Feet*CostPerFoots之后计数,因此即使"只是"CostPerFoott之前没有分配任何值…也会发生错误)。
在你的情况下,有两种可能的选择:
1.)任一
//Determine cost per foot of wood
if (radPine.Checked)
{
CostPerFoot = PineCost;
}
else if (radOak.Checked)
{
CostPerFoot = OakCost;
}
else if (radCherry.Checked)
{
CostPerFoot = CherryCost;
}
results in CostPerFoot not to be set (aka none of the three text boxes were set).
或2.)英尺从未设置为值
从你给出的例子来看,不清楚它可能是两种选择中的哪一种,也不清楚它是否同时存在。因此,您需要同时选中这两个复选框,如果这两个选项都可能未选中,请创建一个else路径,将CostPerFoot设置为默认值(或在if结构之前设置)。对于Feet,你需要检查你给出的代码上方的所有代码,看看它是否被设置为任何值(或者是否在if中完成,如果if总是true,如果不是……将默认值放入else路径)。