簡體   English   中英

為什么我收到“System.InvalidCastException: Specified cast is not valid”?

[英]Why am I getting "System.InvalidCastException: Specified cast is not valid"?

此代碼用於使用System.Data.SqlClient的 C# SqlDatAdapter 從 SQL 服務器獲取我的圖書館應用程序中的所有書籍。 這是將所有書籍添加到List<Book> ,其中 book 是聲明的對象類。

allBooks.Add(new Book((String)i["title"], (String)i["author"], (Boolean)i["checkedOut"], (String)i["checkedOutTo"], (DateTime)i["dueDate"], (Double)i["Dues"], (int)i["extensions"], (String)i["imageURL"], (String)i["description"]));

當你有這個位置時,你必須把那一行分割成多於一個代碼行。 使用臨時變量來存儲每個數組訪問 + 轉換操作的其余部分。 這樣你就會得到一個有意義的線路/操作,這就是問題所在。 像這樣的東西:

string title = i["title"];
string author = i["author"];
//lines omited

Book temp = new Book (title, author /*remaining temporary variables*/);
allBooks.Add(temp);

不要擔心由此產生的任何性能或內存影響。 普通編譯器和 JiT 編譯器非常擅長確定它可以在發布版本中刪除這些變量。 有時它們甚至在 Debug 版本中也很好,強制異常可能很困難。

暫無
暫無

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

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