问题描述
我在 Sharepoint 中使用了一小段代码,如下所示:
I was working with a small piece of code in Sharepoint, that goes like this:
int? do_ = (int?)re["mi"]; // consider "re" a dictionary<string, object>;
等号右侧的表达式计算结果为 Double
.为了确保double
,我在观察窗口中double
-检查了它(:D).是的,它是一个 System.Double
,进进出出.
The expression to the right of the equal sign evaluates to a Double
. To make double
sure, I double
-checked it (:D) in the watch window. And yeah, it's a System.Double
, in and out.
但是,该行引发异常:
指定的演员表无效.
当我意识到是的,您可以将 double 转换为 int 时,我正要用我的额头在我的桌子上做个凹痕,但会丢失值的非整数部分(这实际上是我的目的).我在编程的第一天就学会了这一点,当时世界还没有发生变化.
I was about to make a dent on my desk with my forehead when it dawned on me that yes, you can cast double to int, though losing the non-integer part of the value (which is actually intended in my case). I learned this in my first days of programming, before the world moved on.
为了更加确定,我创建了另一个解决方案,一个简单的控制台应用程序.我把这段代码放进去:
So to be even more sure, I created another solution, a simple console app. I put this code into it:
double dragon = 2.0;
int? i = (int?)dragon;
它可以正常工作,正如预期的那样.
And it works, just as expected.
为什么它在一种设置中有效,而在另一种设置中失败?
Why would it work in one setting but fail in the other one?
推荐答案
这是一个非常常见的问题.除了 T
或 T?
之外,您不能将装箱的 T
拆箱到任何东西.
This is a very frequently asked question. You cannot unbox a boxed T
to anything other than T
or T?
.
我在这里解释原因:
http://ericlippert.com/2009/03/03/representation-and-identity/
这篇关于无法从 double 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!