DataReader:指定的类型转换无效(Int32)

16

为什么SqlDataReader在将0转换为整数时会抛出异常?

?dataReader(3)
0 {Short}
    Short: 0
?dataReader.GetInt16(3)
0
?dataReader.GetInt32(3)
{"Specified cast is not valid."}
    _HResult: -2147467262
    _message: "Specified cast is not valid."
    Data: {System.Collections.ListDictionaryInternal}
    HelpLink: Nothing
    HResult: -2147467262
    InnerException: Nothing
    IsTransient: False
    Message: "Specified cast is not valid."
    Source: "System.Data"
    StackTrace: "   at System.Data.SqlClient.SqlBuffer.get_Int32()     
                    at System.Data.SqlClient.SqlDataReader.GetInt32(Int32 i)"
    TargetSite: {Int32 get_Int32()}
1个回答

32

这不是转换 - 而是强制类型转换。和下面的代码一样:

short x = 0;
object y = x;
int z = (int)y; // BOOM! InvalidCastException Specified cast is not valid.
在这两种情况下,short 不是 int
如果不确定类型,你可以尝试:
int i = Convert.ToInt32(dataReader.GetValue(3));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接