将字符串列表重写为结构数组不工作-索引错误



我使用struct igralec定义了一个数组播放器,它接受一个字符串和一个整数。我也需要数组player在其他函数中,因为我必须操作里面的数据。

然而,如果我尝试运行整个代码,我会在

行最后一个for循环中得到一个错误。玩家

[我]。

已经在第一个索引i

错误提示:类型为"System"的未处理异常。.

igralec[] player { get; set; }
public struct igralec
    {
        public string Name;
        public int Points;
        public igralec( string ime, int tocke)
        {
            Name = ime;
            Points = tocke;
        }
    }
    public void PlayButton_Click(object sender, EventArgs e)
        {
            List<string> myList = new List<string>();
            //declaring a list of strings to which all the player names are copied
            for (int i = 0; i < PlayersList.Items.Count; i++)
            {
                PlayersList.Items[i].Selected = true; //marking the items from the list as selected
            }
            foreach (ListViewItem Item in PlayersList.SelectedItems)
            {
                myList.Add(Item.Text.ToString()); //add to list all selected items
            }
            if (PlayersList.Items.Count != 0 && SteviloTock.SelectedItem != null) {
                //collect the data in struct vector so I can use it outside this function
                player = new igralec[] { };
                //rewrite the array so you can use it outside the function
                for (int i = 0; i < myList.Count; i++)
                {
                    player[i].Name = myList[i];
                    player[i].Points = StTock;
                }
            }
        }

这里有什么问题?

您已经创建了一个新的数组player = new igralec[] { };,然后立即尝试访问数组i = 0, player[i].Name = myList[i];中的第一个元素

player[0]还不存在(空数组),因此抛出System.IndexOutOfRangeException。你需要在玩家集合中添加一个新元素。

如果你在创建集合时不知道数组的大小,你可以考虑使用List,就像在c#数组中添加值:

List<igralec> igralecList = new List<igralec>();
for (int i = 0; i < myList.Count; i++)
{
    igralecList.Add(new igralec(myList[i], StTock));
}
// You can convert it back to an array if you would like to
igralec[] igralecArray = igralecList.ToArray();

或者使用lambda表达式(如Andrei Olariu所建议的):

player = myList.Select(i => new igralec(i, StTock)).ToArray();

就像其他人说的,这是因为你的数组没有大小。

你也可以试试这个:

player = myList.Select(i => new igralec(i, StTock)).ToArray();

而不是:

//collect the data in struct vector so I can use it outside this function
player = new igralec[] { };
//rewrite the array so you can use it outside the function
for (int i = 0; i < myList.Count; i++)
{
    player[i].Name = myList[i];
    player[i].Points = StTock;
}

相关内容

  • 没有找到相关文章

最新更新