.net DataReader:指定的强制转换无效 (Int32)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10119336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 16:21:13 来源:igfitidea点击:
DataReader: Specified cast is not valid (Int32)
提问by moldovanu
Why does SqlDataReader throw an exception when converting 0 to integer?
为什么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()}
回答by Marc Gravell
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.
In both cases, a shortis not an int.
在这两种情况下, ashort都不是int。
If unsure of the type, you might try:
如果不确定类型,您可以尝试:
int i = Convert.ToInt32(dataReader.GetValue(3));

