簡體   English   中英

C#System.InvalidCastException:指定的轉換無效

[英]C# System.InvalidCastException: Specified Cast is not valid

在過去的幾個小時中,我一直在努力解決一個問題。

我不斷收到錯誤消息,它告訴我指定的轉換無效。 我可以使用存儲過程更改數據庫上的值。 但是,當我嘗試使用可執行文件執行此操作時,出現該錯誤。

這是錯誤

System.InvalidCastException: Specified cast is not valid.
at Administrator_Panel.DB.ReadAccountInfo(String UserID, In32& Count)

這是代碼。

 public static Account ReadAccountInfo(string UserID, out int Count)

 if (Reader.Read())
                ReturnValue = new Account((int)Reader["UserUID"],
                                            (string)Reader["Pw"],
                                            (bool)Reader["Admin"],
                                            (bool)Reader["Staff"],
                                            (short)Reader["Status"],
                                            (int)Reader["Point"],
                                            (int)Reader["DaemonPoints"]);

任何幫助,將不勝感激。 :) 謝謝

看到這個答案: 如何將SQLDataReader字段(有效地)轉換(廣播?)為其對應的C#類型?

由於存在空值的可能性,因此不能僅將SqlDataReader字段轉換為它們的相應值類型。 您可以使用可為空的類型,但很可能您的Account對象未設置為采用可為空的類型。

您可以嘗試處理此問題的一種方法是添加null檢查:

 ReturnValue = new Account(Reader["UserUID"] == DBNull.Value ? 0 : (int)Reader["UserUID"] ,
                           Reader["Pw"] == DBNull.Value ? "" : Reader["Pw"].ToString(),
                           Reader["Admin"] == DBNull.Value ? false : (bool)Reader["Admin"],
                           Reader["Staff"] == DBNull.Value ? false : (bool)Reader["Staff"],
                           Reader["Status"] == DBNull.Value ? (short) 0 : (short)Reader["Status"],
                           Reader["Point"] == DBNull.Value ? 0 :  (int)Reader["Point"],
                           Reader["DaemonPoints"] == DBNull.Value ? 0 : (int)Reader["DaemonPoints"]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM