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

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

我的代码如下:

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

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

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

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

我尝试使用 unchecked,但这也没有用。

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

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

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

find solution

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

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

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

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

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