为什么我不能用三元运算符将null赋值给十进制?
我无法理解为什么这不起作用
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : null;
因为null
是object
类型(实际上是无类型的),您需要将其分配给类型化对象。
这应该工作:
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?
编译器从未考虑过。 在您的情况下, a
和b
的类型是decimal
和一些未知的引用或可空类型。 编译器无法猜出你的意思,所以你需要帮助它:
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : default(decimal?);
你需要将第一部分转换为decimal?
上述就是C#学习教程:为什么我不能用三元运算符将null赋值给十进制?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? (decimal?)decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) : null;
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/991140.html