c# - C# 中的局部变量

标签 c#

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/

相关文章:

c# - 连续负数算法

c# - C#中简单的DES ECB加解密

c# - UWP DatePicker 自定义月份字符串

c# - 打开对话框防止 windows 关闭

c# - Delphi 中的 DataTable(如 DataSet)组件

c# - RawPrinter 助手 : Printer not printing Tamil characters

c# - 如何查找和删除文本文件中的控制字符

c# - 我在某处有隐藏的配置文件吗?

c# - JSON.NET 可以使用 "sidecar"方法序列化对象吗?

c# - 通知方法调用者该方法抛出的异常类型的属性