本文介绍了DataReader:指定的强制类型转换无效(Int32)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么将0转换为整数时SqlDataReader会引发异常?
Why does SqlDataReader throw an exception when converting 0 to integer?
?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()}
推荐答案
这不是a依者,而是演员。等同于:
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.
在两种情况下, short
都不是 int
。
In both cases, a short
is not an int
.
如果不确定类型,可以尝试:
If unsure of the type, you might try:
int i = Convert.ToInt32(dataReader.GetValue(3));
这篇关于DataReader:指定的强制类型转换无效(Int32)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!