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

问题描述 投票:7回答:2

我的代码如下:

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

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

System.InvalidCastException:无法转换类型的对象'System.Int64'键入'System.Int32'。

我不确定为什么我不能只从long转换为int。我知道一个事实,该值小于0xFFFFFF(24位),因为它是一种颜色。

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

c# .net mono xamarin.ios
2个回答
20
投票

您必须首先unbox该值,因为字典的值类型是object

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

0
投票

无法跟踪,因为已经跟踪了另一个具有相同键值的实例

查找解决方案

  context.Patrol.AddRange(model);  // error

entity.Property(e => e.Id)
                    .HasColumnName("ID")
                    .ValueGeneratedNever(); // old

entity.Property(e => e.Id)
                    .HasColumnName("ID"); //remove ValueGeneratedNever()
© www.soinside.com 2019 - 2024. All rights reserved.