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にデフォルト値を指定しないと、コンパイル時にエラーが発生します。他の回答に加えて、あなただけのこのケースで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;
}
例えば は(括弧はわかりやすくするために追加):
double insuranceCost = (this.comboBox5.Text == "Third Party Fire and Theft") ? 1 : 0;
初期化したいどのような値で0
を置き換えinsuranceCost
を条件に一致しない場合
'comboBox5'のテキストが異なる場合、insuranceCostにはどのような価値がありますか? – Heinzi