2015-07-19 45 views
0

我一直在努力解决这几个小时中的一个问题。C#System.InvalidCastException:指定的演员无效

我不断收到错误,它告诉我指定的转换无效。我可以使用存储过程更改数据库上的值。但是,当我尝试使用可执行文件进行操作时,我收到了该错误。

这是错误

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"]); 

任何帮助,将不胜感激。 :)谢谢

+1

后的数据库表定义,查询字符串,客户类的构造函数签名 –

+0

尝试转换,而不是铸造 –

回答

1

看到这个答案:How to (efficiently) convert (cast?) a SqlDataReader field to its corresponding c# type?

你不能只投SqlDataReader领域及其相应的值类型的,因为空值的可能性。您可以使用可为空的类型,但很可能您的Account对象没有设置为可空类型。你可以尝试处理这个

一种方法是增加空检查:

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"]);