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

后端 未结 6 849
故里飘歌
故里飘歌 2021-01-17 08:03

I can\'t understand why this won\'t work

decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text) 
    ? decimal.Parse(txtLineCompRetAmt.Text.R         


        
6条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-17 08:13

    Because the compiler can't infer the best type from the operands of the conditional operator.

    When you write condition ? a : b, there must be an implicit conversion from the type of a to the type of b, or from the type of b to the type of a. The compiler will then infer the type of the whole expression as the target type of this conversion. The fact that you assign it to a variable of type decimal? is never considered by the compiler. In your case, the types of a and b are decimal and some unknown reference or nullable type. The compiler can't guess what you mean, so you need to help it:

    decimal? compRetAmount = !string.IsNullOrEmpty(txtLineCompRetAmt.Text)
                                 ? decimal.Parse(txtLineCompRetAmt.Text.Replace(",",""))
                                 : default(decimal?);
    

提交回复
热议问题