如何在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