简体   繁体   中英

Specified cast is not valid (double precision to int)

Here I need to cast to double precision to integer.

Example :

obj.DayDifference = !string.IsNullOrEmpty(reader["DateDiff"].ToString()) ?   
               (Int32)reader["DateDiff"] : 0;

Type :

  • DayDifference of type int

  • DateDiff of type double precision in the database table .

Error :

Specified cast is not valid

What you're doing is equivalent to:

object x = 32.5;
int y = (int) x;

You can't do that - when you unbox, you have to unbox to the actual type of the value 1 .

So you'd need:

object x = 32.5;
int y = (int) (double) x;

The cast to double unboxes, and the cast to int converts the double to an int . You can do the same in your code:

(Int32)(Double) reader["DateDiff"] : 0;

1 Well, modulo a few things. The CLR allows you to unbox an int to a uint or to an enum type with an underlying type of int , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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