本文介绍了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".
我不知道为什么我不能从 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"类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!