亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何修復 DataReader.GetString() 上的 System.InvalidCast

如何修復 DataReader.GetString() 上的 System.InvalidCast

C#
忽然笑 2023-08-27 10:46:30
問題是:我運行此代碼(代碼1),并在瀏覽器(ASP.NET)中獲得System.InvalidCastException。完全相同的代碼(在我的例子中,我使用另一個項目中的這個函數),在另一個項目中運行并使用相同的數據工作正常,并且不會拋出任何異常。我嘗試捕獲此異常并查看問題對象(代碼 2)的內部,但隨后令我驚訝的是沒有捕獲異常(我在 catch 代碼塊的第二行放置了一個斷點以確保)并且得到了正確的輸出在瀏覽器中代碼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;            }我希望這個函數盡可能快,所以 try-catch 無法解決我的問題。有任何想法嗎?UPD:瀏覽器異常:圖像
查看完整描述

2 回答

?
慕仙森

TA貢獻1827條經驗 獲得超8個贊

我認為的基本答案是,Reader.GetString(i)如果值為 ,則會拋出異常null,因此您必須使用IsDBNull來檢查。

查看完整回答
反對 回復 2023-08-27
?
蕪湖不蕪

TA貢獻1796條經驗 獲得超7個贊

Reader.GetString() 與 object.ToString() 不同。?

UPD:“出現這種情況是因為 SQLiteDataReader 檢查從數據庫文件數據集返回的列數據類型。例如:如果列數據類型是整數并且我們運行 GetString() 方法,SQLiteDataReader 會拋出異常?!?/p>


查看完整回答
反對 回復 2023-08-27
  • 2 回答
  • 0 關注
  • 189 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號