2016-05-09 3 views
4

の値はnullを取得しますは、私は次のモデルを持っているC#6でNULL可能変数

Model model = new Model();  
Int32 result = model.Result.Value; 

結果がnullの場合、私が取得しますエラーが発生するので、私は使用する必要があります:

Int32 result = model.Result.HasValue ? model.Result.Value : 0; 

C#6でこれを行う方法はありますか?

+0

なぜ 'のInt32を提供するために、ヌル条件演算子ではnull-伝搬演算子を使用できますか? result' –

+1

'GetValueOrDefault'を使うことができますが、これは' Int32'に '0'を与えます(あなたは' Int32'にnullを代入することはできません)。 –

+1

'null'は' Int32'型の値ではないので、あなたのサンプルはコンパイルされません。代わりに '0'を使用しますか? – Lee

答えて

6

デフォルトの実装

Model modelWithNullValue = new Model(); 
Model modelWithValue = new Model { Result = 1}; 
Model modelThatIsNull = null; 
Int32 resultWithNullValue = modelWithNullValue?.Result ?? -1; 
Int32 resultWithValue = modelWithValue?.Result ?? -1; 
Int32 resultWithNullModel = modelThatIsNull?.Result ?? -2; 
Console.WriteLine(resultWithNullValue); // Prints -1 
Console.WriteLine(resultWithValue); // Prints 1 
Console.WriteLine(resultWithNullModel); // Prints -2 
+2

'?'と 'model.Result'を直接使うことができます:' int result = model.Result ?? -1; ' – Lee

+0

良い点。反映するための編集。 –

+1

@JonathonChaseあなたは使用できません?.Value –

関連する問題