繁体   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