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
中抛出异常,如果这种情况永远不会发生的话。通过抛出异常来处理无效状态(错误?)是一种很好的做法。这可以防止您忽略它,并防止错误的值被默默地接受。
关于c# - C# 中的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33758145/