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

如何在if语句之外提供insuranceCost

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

在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 

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

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

如果条件不匹配,则将0和要初始化insuranceCost值替换为0

  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; }