c# 转换错误(无限值....什么?)

标签 c# winforms casting dataset

可能我忽略了一些事情,但这个问题让我非常恼火。 我试图从数据集中获取一个值,然后使用它进行一些计算。 在数据集中它被视为一个对象,所以我需要将它转换为 int 或 double。 出于某种原因,我遇到了一个愚蠢的错误,这让我很不安。这是代码。

private void SpendsAnalysis()
    {
        float tempQty = 0;
        float tempPrice = 0;
        double tempTot = 0;
        double total = 0;

        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            tempQty = (float)row.Cells["Qty"].Value;
            tempPrice = (float)row.Cells["Unit"].Value;

            tempTot = tempQty * tempPrice;
            total += tempTot;
        }

        textBox7.Text = total.ToString();
    }

抛出:“指定的类型转换无效。” (System.InvalidCastException) 类型转换数字时,必须小于无穷大。这是我收到的恼人错误。现在我从我的数据集中获取数据,它从存储过程中获取数据。 我相信“数量”字段类型是货币(是的,为什么数量是货币哈哈,而不是我的表!)。在我的数据 GridView 中它看起来像 1.000,这是由于类型转换吗?我将如何纠正这个? 非常感谢!

最佳答案

类型转换必须成功,不幸的是,直接从 object 进行转换与底层对象不同的类型是行不通的,即使从 decimal 进行转换也是如此(currency 的 .NET 类型)到 float通常会工作。

如果数据库中的类型是currency ,我会试试这个:

= (float)(decimal)row.Cells["Qty"].Value;

或者,您可以使用 this :

= Convert.ToSingle(row.Cells["Qty"].Value);

它将查看实际值并确定要执行的正确转换类型。

为了回答您的评论,上面的表达式涉及两个不同的转换:

  • 来自 object 的拆箱转换到值类型,在本例中为 decimal
  • decimal 的显式转换至 float

第一个是拆箱转换,记录在 C# 语言规范第 4.3.2 节(这是 C# 4.0 specification ):

An unboxing operation to a non-nullable-value-type consists of first checking that the object instance is a boxed value of the given non-nullable-value-type, and then copying the value out of the instance.

(我的重点)

我还有规范的注释版本,Eric Lippert 将其总结为:

Although it is legal to convert an unboxed int to an unboxed double, it is not legal to convert a boxed int to an unboxed double—only to an unboxed int.

第二种,显式转换,记录在 C# 语言规范第 6.2.1 节中:

6.2.1 Explicit Numeric Conversions
The explicit numeric conversions are the conversions from a numeric-type to another numeric-type for which an implicit numeric conversion (§6.1.2) does not already exist:
...
From decimal to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, or double.

(再次强调)

总结:

  • object 中“转换”时对于值类型,您实际上是在拆箱装箱的值,并且您首先必须将实际的基础值拆箱为其正确的类型,然后才能将其转换为不同的类型。

关于c# 转换错误(无限值....什么?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8428424/

相关文章:

c# - 将字符串转换为 float 并对其进行格式化 (C#)

C# NET4.0 任务保持引用

c# 固定数组 - 从哪个结构读取最快?

c# - 如何计算数字的正确宽度(以像素为单位)?

c# - 关于dataGridView的Row和Column Headers的问题

c - 如何从 argv 将整数传递到 pthread_create 函数? (C)

c# - 在 OnActionExecuting 期间以不同方式处理 GET 和 POST

winforms - cefsharp 中的 cef.pak 文件的用途是什么?

c# - 如何在 C# 中将 UIntPtr 对象转换为 IntPtr?

Java - 将子类传递给类型为父类(super class)的构造函数