2012-04-12 75 views
7

爲什麼SqlDataReader在將0轉換爲整數時會引發異常?DataReader:指定的轉換無效(Int32)

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

回答

22

它不是一個轉換 - 它是一個演員。同爲:

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)); 
相關問題