Cannot implicitly convert type 'decimal?' to 'decimal'.

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

sdr is my sqldatareader and I want to check that the curPrice value which is of type decimal is null.

inrec.curPrice = sdr.IsDBNull(7) ? (decimal?)null : sdr.GetDecimal(7);

This is the error message I am getting:

Cannot implicitly convert type 'decimal?' to 'decimal'. An explicit conversion exists (are you missing a cast?)

Where am I going wrong, please someone tell me.

回答1:

either convert curPrice to nullable, or use .Value property of nullable types.

If curPrice is a property of a class then

public decimal? curPrice {    get;    set; } 


回答2:

decimal? indicates that it's a nullable decimal; you have to use the Value property to get the actual value (if it exists, determined via HasValue).

I'm assuming curPrice is a non-nullable decimal, in which case you need to also figure out a better value to return than null from the true side of your ternary operator.



回答3:

inrec.curPrice = sdr.GetValueOrDefault(0m) 

Since the left side (Price) does not allow for null then you cannot set its value to something that could be null. Therefore, use .GetValueOrDefault(decimal defaultValue) to return a default value when null.



回答4:

How about converting the decmial? type to decimal ?

You have to have what value you like inrec.curPrice to have when sdr.GetDecmial(7) is null.

inrec.curPrice = sdr.GetDecimal(7) ?? 0M; 

I assumed that you would want to use 0 if what's returned was null. If not change 0M to some other decimal value.

--- Update after replay

How about inrec.curPrice = sdr.IsDBNull(7) ? 0M : sdr.GetDecimal(7); ?



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!