C#windows窗体程序中的"指定的强制转换无效"错误

jel*_*llo 13 c# sql-server

我有一个"指定演员阵容无效"错误.C#中的Windows表单应用程序.我正在尝试从表中检索值.该值是smallint或数字(我试过两个字段,都给我相同的错误),我尝试将它存储在一个int变量中.

这里是来源:

using (SqlDataReader rdr = cmd.ExecuteReader()) //"select * from table where fieldname = " + value
{

 while (rdr.Read())
 {
  int number = (int)rdr["quantity"]; // error is here
Run Code Online (Sandbox Code Playgroud)

jas*_*son 19

rdr["quantity"]将是一个盒装的东西.如果它不是int那么你就不能直接将它拆箱到int(这是你想要做的),因为你必须首先将它拆箱到适当的类型(比方说short).但这太麻烦了,为了清楚起见,你最好说

Convert.ToInt32(rdr["quantity"]);
Run Code Online (Sandbox Code Playgroud)


小智 5

  if(rdr["quantity"].GetType() != typeof(int))
    throw new InvalidOperationException(
      "quantity is a " + rdr["quantity"].GetType());
  int number = (int)rdr["quantity"]; // error is here
Run Code Online (Sandbox Code Playgroud)

  • @jello是的,您可能知道数据库中的数据类型,但您*显然*不知道.NET等效类型是什么,或者它的DBNULL,因此"指定的强制转换无效"消息. (2认同)