C#:无法将'System.Int64'类型的对象强制转换为'System.Int32'

Kos*_*ukh 7 .net c# mono xamarin.ios

我的代码如下:

Dictionary<object, object> dict = ...
Color = (int)dict.GetValue("color");
Run Code Online (Sandbox Code Playgroud)

当我将Color转换为int时,我得到以下异常:

System.InvalidCastException:无法将类型为"System.Int64"的对象强制转换为"System.Int32".

我不知道为什么我不能只是从长时间转换为int.我知道这个值小于0xFFFFFF(24位),因为它是一种颜色.

我尝试过使用,unchecked但也没用.

Mat*_*hew 20

您必须首先将值取消,因为字典的值类型是object.

Dictionary<object, object> dict = ...
Color = (int)(long)dict.GetValue("color");
Run Code Online (Sandbox Code Playgroud)


Ryo*_*sai 5

如果你不知道原始类型,下面的成语可能更方便。

public T Get<T>(string key)
{
    return (T) Convert.ChangeType(_dict[key], typeof(T), CultureInfo.InvariantCulture);
}
Run Code Online (Sandbox Code Playgroud)