C#中的局部变量

时间:2015-11-17 13:27:01

标签: c#

来自本地变量的C#错误。我收到错误“使用未分配的本地变量'CostPerFoot'”

conio

特别是最后几行

conio.h

尝试切换变量,但仍然存在问题。

3 个答案:

答案 0 :(得分:9)

您收到此错误是因为编译器假定您可能使用变量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中抛出异常,如果这种情况永远不会发生的话。通过抛出异常来处理无效状态(错误?)是一种很好的做法。这可以防止你忽略它并且默默地采取错误的值。

答案 1 :(得分:0)

事实上,编译器因为这一行而抱怨:

CostEstimate = Feet * CostPerFoot; 

由于您的if-else-if块不包含else语句,因此有可能使CostPerFoot var值未初始化,因此在上面的行中计算出现问题。

答案 2 :(得分:0)

您遇到的问题:

  

使用未分配的本地变量

非常“轻松”。它只是意味着你有一个你使用的变量(在if或某种操作中,......)但你在使用之前从未为它赋值。

因此,如果您在以下语句中出现以下错误:

 CostEstimate = Feet * CostPerFoot;

这意味着在使用Feet或CostPerFoot之前从未为其分配过值(= CostEstimate,因此分配仅在计算Feet * CostPerFoot之后计算,因此即使它是“仅”未分配的CostPerFoot之前的任何值......发生错误)。

在您的情况下,有两种可能的选择:

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).

OR 2.)脚从未设置为值

从您给出的示例中,不清楚它可能是哪一个,或者它是否是两个选项都出现在那里。因此,您需要检查两者,如果有可能没有选中复选框,请创建一个将CostPerFoot设置为默认值的else路径(或者在if结构之前设置它)。对于Feet,你需要检查你给出的代码之上的所有代码,看看它是否被设置为任何值(或者如果它是if if if if if if always is true,如果不是.....放一个默认值进入else路径)。

相关问题