DataReader的:指定的转换是无效的(Int32)已(DataReader: Specifie

2019-06-23 13:41发布

为什么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()}

Answer 1:

这不是一个转换 - 这是一个演员。 同为:

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));


文章来源: DataReader: Specified cast is not valid (Int32)