.net - DataReader:指定的强制转换无效 (Int32)

标签 .net sqldatareader datareader

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

最佳答案

这不是皈依 - 这是 Actor 。等同于:

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

关于.net - DataReader:指定的强制转换无效 (Int32),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10119336/

相关文章:

c# - Lambda 和 Expression.Call 扩展方法

c# - 在 vb.net 中隐式实例化的对象?

c# - 如何在 C# 中使用 SqlDataReader 获取行数

sqldatareader - 为什么要使用SqlDataReader的GetOrdinal()方法

linq - 将 dataReader 转换为 Dictionary

c# - BindingList 投影包装器

.net - 如何在正在运行的容器中获取AWS Fargate任务实例元数据?

c# - SqlDataReader 显示 InvalidCastException(C# Windows 窗体)

c# - 已经有一个打开的 DataReader 与此命令关联,必须先关闭 linq

c# - SQL DataReader 网络使用限制