【问题标题】:DataReader: Specified cast is not valid (Int32)DataReader:指定的强制转换无效 (Int32)
【发布时间】:2012-04-24 13:10:21
【问题描述】:

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

【问题讨论】:

    标签: .net sqldatareader datareader


    【解决方案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));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-27
      • 2014-07-30
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多