c# - 为什么我不能使用三元运算符将 null 分配给 decimal?

标签 c# asp.net

我不明白为什么这行不通

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?);

这是 default 的 MSDN 链接关键字。

关于c# - 为什么我不能使用三元运算符将 null 分配给 decimal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9308443/

相关文章:

asp.net - 使用比较验证器失火进行开始日期 - 结束日期验证

c# - Asp.Net 按钮单击 UpdatePanel 内的 Repeater 内的事件

c# - 什么是合适的 NHibernate/Iesi.Collections.Generic.ISet<T> 替代品?

c# - AutoMapper IQueryable Extension 抛出 "Cannot compare elements of type <Complex Type>"

c# - 使用 NHaml 在 HtmlHelper 中缺少扩展方法

javascript - 没有回发的文本框上的 ASP.NET 客户端验证

asp.net - 配置Visual Studio或Chrome以在同一新的浏览器窗口中启动多个Asp.Net项目

c# - 如何找出字节的格式?南音频

c# - 如何开始使用 ReflectInsight?

c# - .NET 控件的最佳开源是什么?