访问'if'语句之外的变量

时间:2012-07-26 07:19:38

标签: c#

如何在insuranceCost声明之外提供if

if (this.comboBox5.Text == "Third Party Fire and Theft")
{
    double insuranceCost = 1;
}

3 个答案:

答案 0 :(得分:15)

在if语句之外定义它。

double insuranceCost;
if (this.comboBox5.Text == "Third Party Fire and Theft")
        {
          insuranceCost = 1;
        }

如果从方法返回,则可以为其指定默认值或0,否则可能会出现错误“使用未分配的变量”;

double insuranceCost = 0;

double insuranceCost = default(double); // which is 0.0

答案 1 :(得分:4)

除了其他答案之外,您可以在这种情况下内联if(仅为了清晰起见而添加括号):

double insuranceCost = (this.comboBox5.Text == "Third Party Fire and Theft") ? 1 : 0; 

如果条件不匹配,请将0替换为您要初始化insuranceCost的任何值。

答案 2 :(得分:3)

    double insuranceCost = 0; 
    if (this.comboBox5.Text == "Third Party Fire and Theft") 
    { 
        insuranceCost = 1; 

    } 

在if语句之前声明它,给出一个默认值。在if中设置值。 如果您没有为double提供默认值,则在编译时会出现错误。 例如

double GetInsuranceCost()
{
        double insuranceCost = 0; 
        if (this.comboBox5.Text == "Third Party Fire and Theft") 
        { 
            insuranceCost = 1; 

        } 
        // Without the initialization before the IF this code will not compile
        return insuranceCost;
}