代码之家  ›  专栏  ›  技术社区  ›  Daniel

C对象不解析为int

  •  0
  • Daniel  · 技术社区  · 7 年前

    我的代码如下:

    var score = ((Dictionary<string, object>)entry.Value)["score"];
    print("score: " + score + "!");
    FBManager.instance.friends[id].score = (int) score;
    
    
    //OUTPUT: 
    //score: 5!
    //InvalidCastException: Specified cast is not valid.
    

    为什么我不能投 score 到int?

    我很确定 entry.Value 是一个 Dictionary<string, object> 因为我印刷了 entry.Value.GetType() 它说的正是这个。

    1 回复  |  直到 7 年前
        1
  •  2
  •   Mirko    7 年前

    看看当你这样做的时候你会得到什么: Console.WriteLine(score.GetType())

    如果是system.string,则需要转换(convert.toint32(score))或int.parse(score)。如果是System.Int32,则可以进行铸造。如果它是其他值(双精度、十进制等),只需执行转换操作:)

    祝你好运!