将包含int的对象强制转换为float会导致InvalidCastException [英] Cast object containing int to float results in InvalidCastException

查看:88
本文介绍了将包含int的对象强制转换为float会导致InvalidCastException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    var fP18VaR = (float) (int)e.Values[0];
}

我得到


InvalidCastException-指定的转换无效

InvalidCastException - Specified cast is not valid

为什么不起作用?

e.Values [0]的值为:6 666,00

The value of e.Values[0] is: 6 666,00

推荐答案

这里遇到的问题是C#强制转换运算符在不同情况下的含义不同。

The problem you're running into here is that the C# cast operator means different things in different situations.

以您给出的示例为例:

object num = 10;
float fnum = (float)num;

C#编译器会认为您是这样说的:变量num表示装箱的float;请取消装箱并返回装箱的值。

The C# compiler will think you are telling it this: "The variable num refers to a boxed float; please unbox it and return the boxed value."

您会收到一个错误消息,因为它不是装箱的float,而是装箱的int。

You're getting an error because it's not a boxed float, it's a boxed int.

问题是C#对两个完全不相关的操作使用相同的语法: unbox和 numeric conversion。下面是一个强制转换表示数字转换的示例:

The problem is that C# uses identical-looking syntax for two totally unrelated operations: 'unbox' and 'numeric conversion'. Here's an example of where a cast means numeric conversion:

int num = 10;
float fnum = (float)num;

几乎完全相同的代码,但这不会给您带来错误。那是因为C#编译器对待这一点完全不同-此代码意味着:请执行数字转换,将存储在'num'中的整数转换为单精度浮点值。

Almost exactly the same code, and yet this won't give you an error. And that's because the C# compiler treats this completely differently - this code means: "Please perform a numeric conversion, converting the integer stored in 'num' into a single-precision floating point value."

您如何知道它将选择这两个完全无关的操作?全部与来源和目的地类型有关。如果您要从对象转换为值类型,则始终将其视为取消选中框。如果您要从一种数字类型转换为另一种数字类型,则始终将其视为数字转换。

How do you know which of these two utterly unrelated operations it's going to choose? It's all about the source and destination types. If you're converting from 'object' to a value type, that will always be treated as an unbox. If you're converting from one numeric type to another, that will always be treated as a numeric conversion.

那么如何获得所需的结果?好吧,您需要同时执行这两种操作:您需要将int拆箱,然后将其转换为float。因此,您实际上需要两次强制转换:

So how do you get the result you want? Well, you need to do both operations: you need to unbox the int and then you need to convert it to a float. So you actually need two casts:

object num = 10;
float fnum = (float) (int)num; 

糟糕吧?

最简单的方法在这里要做的是避免完全投射。只是这样做:

The simplest way to do what you want here is to avoid casting entirely. Just do this:

float fnum = Convert.ToSingle(num); 

如果可能的话,这会将类型强制为单精度浮点数。

That will coerce the type to a single-precision float if it's possible to do so.

这篇关于将包含int的对象强制转换为float会导致InvalidCastException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆