为什么我不能用三元运算符将null赋值给十进制?

我无法理解为什么这不起作用

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : null; 

因为nullobject类型(实际上是无类型的),您需要将其分配给类型化对象。

这应该工作:

 decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : (decimal?)null; 

或者这更好一点:

 decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : default(decimal?); 

以下是默认关键字的MSDN链接。

不要使用decimal.Parse

如果给出一个空字符串, Convert.ToDecimal将返回0。 如果要解析的字符串为null, decimal.Parse将抛出ArgumentNullException。

试试这个:

 decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",", "")) : (decimal?) null; 

问题是编译器不知道null有什么类型。 所以你可以把它转换为decimal?

 decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : (decimal?)null; 

因为编译器无法从条件运算符的操作数中推断出最佳类型。

condition ? a : b condition ? a : b ,必须有从a的类型到b的类型的隐式转换,或者从b的类型到b的类型的隐式转换。 然后,编译器将推断整个表达式的类型作为此转换的目标类型。 您将其分配给decimal?类型的变量的事实decimal? 编译器从未考虑过。 在您的情况下, ab的类型是decimal和一些未知的引用或可空类型。 编译器无法猜出你的意思,所以你需要帮助它:

 decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : default(decimal?); 

你需要将第一部分转换为decimal?

 decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? (decimal?)decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : null;