我如何解决 C# 中的 system.invalidcastexception 错误

how can i solve system.invalidcastexception error in c#

当我在 运行 我的代码中时,我在 ** quote

的第 8 行收到一个无效的强制转换异常错误
MySqlCommand cmd = Conn.CreateCommand();
cmd.CommandText = "select type, sum(bottles) as 'total' from creamtable group by type";

MySqlDataReader ResultSet = cmd.ExecuteReader();

List<Cream> totalcream = new List<Cream> { };

while (ResultSet.Read())
{
    string type = ResultSet["type"].ToString();
    **int bottles = (int)ResultSet["total"];**

    Cream c = new Cream();
    c.type = type;
    c.bottles = bottles;
    totalcream.Add(c);
}

嗯,ResultSet["total"]returnsobject,也就是参考类型。如果实际值是值类型intlongdouble等)它将是boxed.在拳击的情况下,一个简单的转换是 restricted:

   byte b = 123;
   object o = b; // boxing
   int i = (int) o; // run time error, only (byte) cast is OK

   int k = (int) b;            // OK (no boxing) 
   int j = Convert.ToInt32(o); // OK (Convert)

在您的情况下,ResultSet["total"] 很可能是装箱的 longdouble 值。在这种情况下,您可以尝试 Convert

   int bottles = Convert.ToInt32(ResultSet["total"]);