繁体   English   中英

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

[英]how can i solve system.invalidcastexception error in c#

当我运行我的代码时,我在 ** 引用的第 8 行收到一个 invalidcastexception 错误

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"]返回object ,它是引用类型 如果实际值是值类型intlongdouble等),它将被装箱 在拳击的情况下,简单的演员阵容受到限制

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM