C# 无法隐式转换类型“十进制”?到'十进制'。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10523885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 14:11:32  来源:igfitidea点击:

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

c#castingdbnullexplicit-conversion

提问by user1270384

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

sdr 是我的 sqldatareader,我想检查十进制类型的 curPrice 值是否为空。

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

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.

我哪里错了,请有人告诉我。

采纳答案by Kishore Kumar

either convert curPriceto nullable, or use .Value property of nullable types.

要么转换curPrice为可空,要么使用可空类型的 .Value 属性。

If curPriceis a property of a class then

如果curPrice是一个类的属性,那么

public decimal? curPrice
{
   get;
   set;
}

回答by ravuya

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

decimal?表示它是一个空的小数;您必须使用该Value属性来获取实际值(如果存在,则通过 确定HasValue)。

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

我假设curPrice是一个不可为空的小数,在这种情况下,您还需要找出比null从三元运算符的真实侧返回更好的值。

回答by Shintaro Sasaki

How about converting the decmial?type to decimal?

如何将decmial?类型转换为decimal

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

inrec.curPricesdr.GetDecmial(7)为空时,您必须拥有您喜欢拥有的值。

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

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

我假设如果返回的内容为空,您会想要使用 0。如果不更改0M为其他一些十进制值。

--- Update after replay

--- 重播后更新

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

怎么样inrec.curPrice = sdr.IsDBNull(7) ? 0M : sdr.GetDecimal(7);

回答by LazyDog

inrec.curPrice = sdr.GetValueOrDefault(0m)

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

由于左侧 ( Price) 不允许,null因此您不能将其值设置为可能为 的值null。因此,使用.GetValueOrDefault(decimal defaultValue)时返回默认值null