如何在if
语句之外提供insuranceCost
?访问'if'语句之外的变量
if (this.comboBox5.Text == "Third Party Fire and Theft")
{
double insuranceCost = 1;
}
如何在if
语句之外提供insuranceCost
?访问'if'语句之外的变量
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
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;
}
除了其他的答案,你可以只内嵌在这种情况下,if
(只添加为清楚起见括号):
double insuranceCost = (this.comboBox5.Text == "Third Party Fire and Theft") ? 1 : 0;
替换0
与您要初始化的任何值如果条件不匹配,则为insuranceCost
。
如果'comboBox5'的文本不同,保险费会有什么价值? – Heinzi 2012-07-26 07:21:41