16

0を整数に変換するときにSqlDataReaderが例外をスローするのはなぜですか?

?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()}
4

1 に答える 1

32

これは変換ではなく、キャストです。と同じ:

short x = 0;
object y = x;
int z = (int)y; // BOOM! InvalidCastException Specified cast is not valid.

どちらの場合も、 ashortは ではありませんint

タイプがわからない場合は、次を試してください。

int i = Convert.ToInt32(dataReader.GetValue(3));
于 2012-04-12T07:37:18.783 に答える