为什么我不能拆箱一个int作为小数点? [英] Why can't I unbox an int as a decimal?
问题描述
我有一个 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):
- 拳击(
箱
IL指令)和拆箱(拆箱
IL指令) - 通过inhertiance层次铸件(如
的dynamic_cast<类型>在C ++
,使用castclass
IL指令验证) - 原始类型之间铸造(如
的static_cast<类型>
在C ++中,有很多不同类型的原始类型之间的强制类型转换的IL指令) - 调用用户自定义转换操作符(在IL水平,他们只是方法调用相应的
op_XXX
法)。
- Boxing (
box
IL instruction) and unboxing (unbox
IL instruction) - Casting through the inhertiance hierarchy (like
dynamic_cast<Type>
in C++, usescastclass
IL instruction to verify) - Casting between primitive types (like
static_cast<Type>
in C++, there are plenty of IL instructions for different types of casts between primitive types) - Calling user defined conversion operators (at the IL level they are just method calls to the appropriate
op_XXX
method).
这篇关于为什么我不能拆箱一个int作为小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!