2012-07-26 149 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