为什么我不能拆箱一个int作为小数点? [英] Why can't I unbox an int as a decimal?

查看:130
本文介绍了为什么我不能拆箱一个int作为小数点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 IDataRecord读我是从如下检索十进制:

I have an IDataRecord reader that I'm retrieving a decimal from as follows:

decimal d = (decimal)reader[0];

由于某些原因,这将引发一个无效的转换异常说,指定的转换是无效的。

For some reason this throws an invalid cast exception saying that the "Specified cast is not valid."

当我这样做阅读[0] .GetType()它告诉我,这是一个Int32。据我所知,这不应该是一个问题....

When I do reader[0].GetType() it tells me that it is an Int32. As far as I know, this shouldn't be a problem....

我这个片断这工作只是正常测试了这一点。

I've tested this out by this snippet which works just fine.

int i = 3750;
decimal d = (decimal)i;

这给我留下了抓我的头不知道为什么它不能拆箱的int包含在读者为十进制。

This has left me scratching my head wondering why it is failing to unbox the int contained in the reader as a decimal.

有谁知道为什么这可能是发生?有什么微妙的我失踪?

Does anyone know why this might be occurring? Is there something subtle I'm missing?

推荐答案

您只能拆箱值类型到其原始类型(以及该类型的可空版本)。

You can only unbox a value type to its original type (and the nullable version of that type).

顺便说一句,这是有效的(只是一个速记你的两个行版本):

By the way, this is valid (just a shorthand for your two line version):

object i = 4;
decimal d = (decimal)(int)i; // works even w/o decimal as it's a widening conversion

有关这背后的原因阅读埃里克利珀的博客条目:重新presentation和身份

For the reason behind this read this Eric Lippert's blog entry: Representation and Identity

我个人的东西分类由投语法做分为四个不同类型的操作(它们都具有不同的IL指令):

Personally, I categorize things done by cast syntax into four different types of operation (they all have different IL instructions):


  1. 拳击( IL指令)和拆箱(拆箱 IL指令)

  2. 通过inhertiance层次铸件(如的dynamic_cast<类型>在C ++ ,使用 castclass IL指令验证)

  3. 原始类型之间铸造(如的static_cast<类型> 在C ++中,有很多不同类型的原始类型之间的强制类型转换的IL指令)

  4. 调用用户自定义转换操作符(在IL水平,他们只是方法调用相应的 op_XXX 法)。

  1. Boxing (box IL instruction) and unboxing (unbox IL instruction)
  2. Casting through the inhertiance hierarchy (like dynamic_cast<Type> in C++, uses castclass IL instruction to verify)
  3. Casting between primitive types (like static_cast<Type> in C++, there are plenty of IL instructions for different types of casts between primitive types)
  4. Calling user defined conversion operators (at the IL level they are just method calls to the appropriate op_XXX method).

这篇关于为什么我不能拆箱一个int作为小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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