繁体   English   中英

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

[英]Why can't I assign null to decimal with ternary operator?

我不明白为什么这不起作用

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到的类型a 然后,编译器将推断整个表达式的类型作为此转换的目标类型。 您将它分配给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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM