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

Zo *_*Has 18 c# asp.net

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

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) 
    ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) 
    : null;
Run Code Online (Sandbox Code Playgroud)

slu*_*ter 47

因为null是类型object(有效无类型),您需要将其分配给类型化对象.

这应该工作:

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) 
         ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) 
         : (decimal?)null;
Run Code Online (Sandbox Code Playgroud)

或者这更好一点:

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) 
         ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",","")) 
         : default(decimal?);
Run Code Online (Sandbox Code Playgroud)

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

  • 最好的回答是不仅仅回答而是通知和教育的回答..好的一个高峰 (3认同)
  • 疯子! (2认同)

Eba*_*ood 7

不要用decimal.Parse.

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


jue*_*n d 5

试试这个:

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) ? 
                         decimal.Parse(txtLineCompRetAmt.Text.Replace(",", "")) : 
                         (decimal?) null;
Run Code Online (Sandbox Code Playgroud)

问题是编译器不知道null具有什么类型.所以你可以把它投到decimal?