6

我怎样才能insuranceCostif声明之外提供?

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

3 回答 3

16

在 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
于 2012-07-26T07:20:36.887 回答
5

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

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

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

于 2012-07-26T07:22:35.633 回答
3
    double insuranceCost = 0; 
    if (this.comboBox5.Text == "Third Party Fire and Theft") 
    { 
        insuranceCost = 1; 

    } 

在 if 语句之前声明它,并给出一个默认值。在 if 中设置值。如果你不给双精度值一个默认值,你会在编译时得到一个错误。例如

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;
}
于 2012-07-26T07:20:49.393 回答