繁体   English   中英

System.InvalidCastException:无法将“System.Double”类型的 object 转换为代码中的“System.Int32”类型

[英]System.InvalidCastException: Unable to cast object of type 'System.Double' to type 'System.Int32' in code

我制作了一种方法,可以从数据库中的特定列中获取所有行值,并将它们作为整数转换为列表。 当我在我的个人计算机上运行这段代码时,它就像一个魅力,但在我公司的计算机上,这段代码抛出了一个异常。

这是代码:

static void Main(string[] args)
        {
            int norm = 43;
            List<int> List = new List<int>();

            string connString = ///

            DataTable dt = new DataTable();

            using (OleDbConnection conn = new(connString))
            {
                OleDbCommand cmd = new("SELECT * FROM USERS", conn);

                conn.Open();

                OleDbDataAdapter adapter = new(cmd);

                adapter.Fill(dt);
            }


            try
            {
                if (norm == 33)
                {
                    for (int i = 0; i < 9; i++)
                    {
                        List.Add(Convert.ToInt32(dt.Rows[i].Field<int>(1)));
                    }
                    Console.WriteLine(LeftSegmentIndex(List, 27));
                }
                else if (norm == 43)
                {
                    for (int i = 9; i < dt.Rows.Count; i++)
                    {
                        List.Add(Convert.ToInt32(dt.Rows[i].Field<int>(1)));
                    }
                    Console.WriteLine(LeftSegmentIndex(List, 27));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }


        }

代码抛出以下异常:

System.InvalidCastException: Unable to cast object of type 'System.Double' to type 'System.Int32'.
   at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
   at System.Data.DataRowExtensions.Field[T](DataRow row, Int32 columnIndex)

此异常发生在第 46 行。

数据库有这样的数字:

Soc Art T_c
12  13  11
15  17  13
18  20  16
22  24  19
25  28  23
28  32  26
32  36  30
36  39  35
44  44  44
13  14  12
16  17  14
19  21  17
22  25  21
26  29  24
30  33  28
33  37  32
37  40  36
44  44  44

有人可以解释为什么这个错误会在我的公司计算机上而不是在我的个人计算机上引发吗?

谢谢。

该错误告诉您基础值是double并且您正尝试将其读取为int 如果不同数据库中的类型不同 - 不要假设int ,让Convert.ToInt32完成它的工作:

List.Add(Convert.ToInt32(dt.Rows[i][1]));

暂无
暂无

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

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