我怎样才能insuranceCost
在if
声明之外提供?
if (this.comboBox5.Text == "Third Party Fire and Theft")
{
double insuranceCost = 1;
}
我怎样才能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
除了其他答案之外,您可以if
在这种情况下内联(仅为清楚起见添加括号):
double insuranceCost = (this.comboBox5.Text == "Third Party Fire and Theft") ? 1 : 0;
如果条件不匹配,则替换0
为您要初始化的任何值。insuranceCost
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;
}