使用 GetDecimal 会导致条件表达式出错
Using GetDecimal gives an error in condition expression
您好,我正在使用 GetDecimal()
,但它在条件表达式中给出了一个错误。
Data = varCmd.IsDBNull(2) ? null : varCmd.GetDecimal(2)
因为这给出了一个错误 "Type of conditional expression cannot be determined because there is no implicit conversion between string and decimal "
。什么可以用作 GetDecimal()
的默认值?有帮助吗?
这里的问题是这部分:
Data = varCmd.IsDBNull(2) ? null : varCmd.GetDecimal(2)
^-+^ ^----------+-------^
| |
| +-- Decimal type
+-- not a Decimal type
表达式编译失败,因为编译器无法推断为了使其工作,它必须将最后一部分设为可为 null 的 Decimal,因此它会尝试找到可以容纳 null
,落在 string
,因此出现错误消息。
您需要指定您想要一个可空小数作为结果,假设 Data
也是可空小数。
如果是,这将起作用:
Data = varCmd.IsDBNull(2) ? (Decimal?)null : varCmd.GetDecimal(2)
如果不是,那么如果列是 null
(DBNull
),则您需要决定将什么存储到 Data
中,可能是 0
:
Data = varCmd.IsDBNull(2) ? 0 : varCmd.GetDecimal(2)
您好,我正在使用 GetDecimal()
,但它在条件表达式中给出了一个错误。
Data = varCmd.IsDBNull(2) ? null : varCmd.GetDecimal(2)
因为这给出了一个错误 "Type of conditional expression cannot be determined because there is no implicit conversion between string and decimal "
。什么可以用作 GetDecimal()
的默认值?有帮助吗?
这里的问题是这部分:
Data = varCmd.IsDBNull(2) ? null : varCmd.GetDecimal(2)
^-+^ ^----------+-------^
| |
| +-- Decimal type
+-- not a Decimal type
表达式编译失败,因为编译器无法推断为了使其工作,它必须将最后一部分设为可为 null 的 Decimal,因此它会尝试找到可以容纳 null
,落在 string
,因此出现错误消息。
您需要指定您想要一个可空小数作为结果,假设 Data
也是可空小数。
如果是,这将起作用:
Data = varCmd.IsDBNull(2) ? (Decimal?)null : varCmd.GetDecimal(2)
如果不是,那么如果列是 null
(DBNull
),则您需要决定将什么存储到 Data
中,可能是 0
:
Data = varCmd.IsDBNull(2) ? 0 : varCmd.GetDecimal(2)