2012-07-26 90 views
5

如何在if語句之外提供insuranceCost訪問'if'語句之外的變量

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

如果'comboBox5'的文本不同,保險費會有什麼價值? – Heinzi 2012-07-26 07:21:41

回答

14

在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 
+0

我猜'0'比'default(double)'更清晰。後者通常與通用類型一起使用,在代碼寫入時您無法知道默認值。 – Joey 2012-07-26 07:43:31

+0

@Joey,我同意,我用默認給出一個想法 – Habib 2012-07-26 07:44:43

3
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; 
} 
+0

爲什麼= 0?... – 2012-07-26 07:21:39

+0

因爲你必須初始化一個變量的值,以避免警告。 – Nickon 2012-07-26 07:22:28

+0

若未採取if,則分配默認值 – Steve 2012-07-26 07:24:25

4

除了其他的答案,你可以只內嵌在這種情況下,if(只添加爲清楚起見括號):

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

替換0與您要初始化的任何值如果條件不匹配,則爲insuranceCost