简体   繁体   English

指定的强制转换无效-十进制

[英]Specified cast is not valid - Decimal

I'm trying to declare a decimal number which will take the value of dr["index"] or the value null if dr["index"] is null. 我正在尝试声明一个十进制数字,如果dr [“ index”]为null,则将采用dr [“ index”]的值或null。

Here is my line of code : 这是我的代码行:

Decimal number = (Decimal)(dr["index"] ?? 0);

I got the following error : 我收到以下错误:

System.Invalid.CastException : 'Specified cast is not valid' 

Would you know how to fix that problem ? 您知道如何解决该问题吗?

I'd go with in case of DBNull.Value: 如果要使用DBNull.Value,我会选择:

Convert.ToDecimal(dr["index"] == DBNull.Value ? 0m : dr["index"])

or in case of null value: 或如果为空值:

Convert.ToDecimal(dr["index"] ?? 0m)

If dr[index] can only be a numeric value. 如果dr[index]只能是一个数字值。

I recommend to use Decimal.TryParse instead: 我建议改用Decimal.TryParse

Decimal d = 0;
if(Decimal.TryParse(dr["index"].ToString(), out d)) {
// Do some stuff here...
}
else {
// Connot Parse, do some other stuff...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM