C# ?: Conditional Operator

后端 未结 8 1746
醉梦人生
醉梦人生 2020-12-05 06:26

I have this extract of C# 2.0 source code:

object valueFromDatabase;
decimal result;
valueFromDatabase = DBNull.Value;

result = (decimal)(valueFromDatabase          


        
相关标签:
8条回答
  • 2020-12-05 07:13

    Your line should be:

    result = valueFromDatabase != DBNull.value ? (decimal)valueFromDatabase : 0m;
    

    0m is the decimal constant for zero

    Both parts of a conditional operator should evaluate to the same data type

    0 讨论(0)
  • The difference is that the compiler can not determine a data type that is a good match between Object and Int32.

    You can explicitly cast the int value to object to get the same data type in the second and third operand so that it compiles, but that of couse means that you are boxing and unboxing the value:

    result = (decimal)(valueFromDatabase != DBNull.value ? valueFromDatabase : (object)0);
    

    That will compile, but not run. You have to box a decimal value to unbox as a decimal value:

    result = (decimal)(valueFromDatabase != DBNull.value ? valueFromDatabase : (object)0M);
    
    0 讨论(0)
提交回复
热议问题