C#:无法将“System.Int64"类型的对象转换为“System.Int32"类型

编程入门 行业动态 更新时间:2024-10-28 00:15:54
本文介绍了C#:无法将“System.Int64"类型的对象转换为“System.Int32"类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的代码如下:

Dictionary<object, object> dict = ... Color = (int)dict.GetValue("color");

当我将 Color 转换为 int 时,出现以下异常:

When I convert the Color to an int, I get the following exception:

System.InvalidCastException:无法转换类型的对象System.Int64"输入System.Int32".

System.InvalidCastException: Unable to cast object of type 'System.Int64' to type 'System.Int32'.

我不知道为什么我不能从 long 转换为 int.我知道该值小于 0xFFFFFF(24 位),因为它是一种颜色.

I am not sure why I can't just cast from a long to an int. I know for a fact that the value is less than 0xFFFFFF (24 bits) since it is a color.

我尝试使用 unchecked 但这也无济于事.

I tried using unchecked but that didn't help either.

推荐答案

您必须首先 unbox 值作为字典的值类型是 object.

You must first unbox the value as the dictionary's value type is object.

Dictionary<object, object> dict = ... Color = (int)(long)dict.GetValue("color");

更多推荐

C#:无法将“System.Int64"类型的对象转换为“System.Int32"类型

本文发布于:2023-05-31 12:03:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/391389.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   转换为   对象   System   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!