-1

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>;

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.

However, that line throws an exception:

Specified cast is not valid.

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?

4

3 回答 3

9

这是一个非常常见的问题。除了或之外,您不能将已装箱T的内容拆箱。 TT?

我在这里解释为什么:

http://ericlippert.com/2009/03/03/representation-and-identity/

于 2013-07-15T20:57:44.330 回答
2

但这应该对你有用

(int?)(double)re["mi"];

Edit1 如果盒装类型为双精度,则上面的代码将起作用,如果double? 要使其起作用,则不起作用,请执行以下操作

(int?)(double?)re["mi"];
于 2013-07-15T20:59:44.580 回答
0

这是因为您试图将对象转换为整数。你的十进制值被装箱了。

精简一下:

object o = 2.0d;

int i = (int)((double) o); // This will work
于 2013-07-15T21:04:49.353 回答