2012-07-26 18 views
5

ifステートメント以外でinsuranceCostを利用できるようにするにはどうすればよいですか?'if'ステートメント以外の変数へのアクセス

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

'comboBox5'のテキストが異なる場合、insuranceCostにはどのような価値がありますか? – Heinzi

答えて

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

+0

@ジョー、私は同意する、私はアイデアを与えるためにデフォルトを使用 – Habib

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

    } 

デフォルト値を与えて、if文の前にそれを宣言します。 if内部の値を設定します。 doubleにデフォルト値を指定しないと、コンパイル時にエラーが発生します。他の回答に加えて、あなただけのこのケースで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; 
} 
+0

なぜ?= 0?... –

+0

警告を避けるために、変数をある値で初期化しなければならないので。 – Nickon

+0

ifを使用しない場合のデフォルト値の割り当て – Steve

4

例えば は(括弧はわかりやすくするために追加):

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

初期化したいどのような値で0を置き換えinsuranceCostを条件に一致しない場合