开发者

.net Trouble casting ints do decimals

Why does this:

(new[]{1,2,3}).Cast<decimal>();

result in an

InvalidCastException: S开发者_运维知识库pecified cast is not valid.


Yup, Cast doesn't do that. Basically it just does reference conversions and unboxing conversions - not conversions between different value types.

Use this instead:

(new[]{1,2,3}).Select(x => (decimal)x)

Note that pre-.NET 3.5 SP1, Cast did some more conversions than it does now. I don't know offhand whether it would have worked then or not, but it definitely doesn't now.


Cast isn't convert.

When you use the Cast extension method, it's trying to cast an item based on the inheritance scheme. Since int doesn't derive from decimal, this can't be done using Cast. Try the following instead:

(new[] {1,2,3}).Select(x => (decimal)X);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜