问题描述
我有一个 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."
当我执行 reader[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
对于这背后的原因,请阅读此 Eric Lippert 的博客条目:Representation and身份
For the reason behind this read this Eric Lippert's blog entry: Representation and Identity
就我个人而言,我将通过 cast 语法所做的事情分为四种不同类型的操作(它们都有不同的 IL 指令):
Personally, I categorize things done by cast syntax into four different types of operation (they all have different IL instructions):
- 装箱(
box
IL指令)和拆箱(unbox
IL指令) - 通过继承层次进行强制转换(如C++中的
dynamic_cast
,使用castclass
IL指令进行验证) - 原始类型之间的转换(如 C++ 中的
static_cast
,有大量 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 拆箱为小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!