我不明白为什么这行不通
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?);
这是 default 的 MSDN 链接关键字。
关于c# - 为什么我不能使用三元运算符将 null 分配给 decimal?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9308443/