問題是:我運(yùn)行此代碼(代碼1),并在瀏覽器(ASP.NET)中獲得System.InvalidCastException。完全相同的代碼(在我的例子中,我使用另一個項(xiàng)目中的這個函數(shù)),在另一個項(xiàng)目中運(yùn)行并使用相同的數(shù)據(jù)工作正常,并且不會拋出任何異常。我嘗試捕獲此異常并查看問題對象(代碼 2)的內(nèi)部,但隨后令我驚訝的是沒有捕獲異常(我在 catch 代碼塊的第二行放置了一個斷點(diǎn)以確保)并且得到了正確的輸出在瀏覽器中代碼1private static List<Dictionary<string, object>> GetResultRows(SQLiteDataReader Reader) { List<Dictionary<string, object>> Result = new List<Dictionary<string, object>>(); if (!Reader.HasRows) return Result; while (Reader.Read()) { var CurrentRow = new Dictionary<string, object>(); Result.Add(CurrentRow); for (int i = 0; i < Reader.FieldCount; i++) { CurrentRow.Add(Reader.GetName(i), Reader.GetString(i)); } } return Result; }代碼2private static List<Dictionary<string, object>> GetResultRows(SQLiteDataReader Reader) { List<Dictionary<string, object>> Result = new List<Dictionary<string, object>>(); if (!Reader.HasRows) return Result; while (Reader.Read()) { var CurrentRow = new Dictionary<string, object>(); Result.Add(CurrentRow); for (int i = 0; i < Reader.FieldCount; i++) { //CurrentRow.Add(Reader.GetName(i), Reader.GetString(i)); try { CurrentRow.Add(Reader.GetName(i), Reader.GetString(i)); } catch { var temp = Reader.GetValue(i); System.Diagnostics.Debug.WriteLine($"{Reader.GetName(i)} = {Reader.GetValue(i)}"); } } } return Result; }我希望這個函數(shù)盡可能快,所以 try-catch 無法解決我的問題。有任何想法嗎?UPD:瀏覽器異常:圖像
2 回答

慕仙森
TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個贊
我認(rèn)為的基本答案是,Reader.GetString(i)
如果值為 ,則會拋出異常null
,因此您必須使用IsDBNull
來檢查。

蕪湖不蕪
TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超7個贊
Reader.GetString() 與 object.ToString() 不同。?
UPD:“出現(xiàn)這種情況是因?yàn)?SQLiteDataReader 檢查從數(shù)據(jù)庫文件數(shù)據(jù)集返回的列數(shù)據(jù)類型。例如:如果列數(shù)據(jù)類型是整數(shù)并且我們運(yùn)行 GetString() 方法,SQLiteDataReader 會拋出異常?!?/p>
- 2 回答
- 0 關(guān)注
- 209 瀏覽
添加回答
舉報(bào)
0/150
提交
取消