UWP使用MVVM并获得此错误

时间:2016-12-20 20:02:41

标签: c# json parsing

所以我正在使用UWP应用程序并且我使用MVVM来解析JSON文件,但有时候(并不总是足以令人担心)我收到此错误:

  

类型' System.ArgumentOutOfRangeException'的例外情况发生在mscorlib.ni.dll但未在用户代码中处理

     

其他信息:指数超出范围。必须是非负数且小于集合的大小。

它始终出现在这一行:

public BackgroundViewModel SelectedGame
    {
        get { return (_SelectedIndex >= 0) ? _game[_SelectedIndex]: null; }
    }

我解析的文本文件也不是那么大:

[{"name" : "BrainBox", "image" : "/Images/BrainBox.jpg"},

{   "name" : "DownToATea", 
    "image" : "/Images/DownToATea.jpg"},

{   "name" : "FoalShadow", 
    "image" : "/Images/FoalShadow.png"},

{   "name" : "GoWithTheBuffLow", 
    "image" : "/Images/GoWithTheBuffLow.jpg"},

{   "name" : "SpotTheDifference", 
    "image" : "/Images/SpotTheDifference.png"}

]

非常感谢任何有关此事的帮助

1 个答案:

答案 0 :(得分:2)

The clue is in the additional information:

An exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.ni.dll but was not handled in user code

Additional information: Index was out of range. Must be non-negative and less than the size of the collection.

We can guess that it might happen in one of the following scenarios:

  1. Classic off by 1 error where _SelectedIndex is 1-based
  2. _SelectedIndex has a default value of 0 even when there is no game to be selected.
  3. A game were removed from _game and _SelectedIndex is still pointing to the last.

Basically, _SelectedIndex has gone out of sync with the number of _games. This can be fixed by restricting the index within the boundaries of the array _game:

return (0 <= _SelectedIndex && _SelectedIndex < _game.Count) ? _game[_SelectedIndex] : null;