开发者

.net Trouble casting ints do decimals

开发者 https://www.devze.com 2022-12-21 13:32 出处:网络
Why does this: (new[]{1,2,3}).Cast<decimal>(); result in an InvalidCastException: S开发者_运维知识库pecified cast is not valid.

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

精彩评论

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