DataReader: Specified cast is not valid (Int32)

后端 未结 1 722
南方客
南方客 2021-01-08 00:56

Why does SqlDataReader throw an exception when converting 0 to integer?

?dataReader(3)
0 {Short}
    Short: 0
?dataReader.GetInt16(3)
0
?dataReader.GetInt32(         


        
相关标签:
1条回答
  • 2021-01-08 01:13

    It isn't a convert - it is a cast. The same as:

    short x = 0;
    object y = x;
    int z = (int)y; // BOOM! InvalidCastException Specified cast is not valid.
    

    In both cases, a short is not an int.

    If unsure of the type, you might try:

    int i = Convert.ToInt32(dataReader.GetValue(3));
    
    0 讨论(0)
提交回复
热议问题