试图循环浏览我的字符,但一旦我在最后一个字符上单击下一步,它就会中断。 visual studio 给出的响应是:ArgumentOutOfRangeException 未处理并引用我的“playerCharacter pc = player[currentPlayerIndex];”
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RPGExample
{
public partial class Form1 : Form
{
private List<PlayerCharacter> player;
int currentPlayerIndex = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// set up an empty list
player = new List<PlayerCharacter>();
// add a couple of players
player.Add(new PlayerCharacter("Attila"));
player.Add(new PlayerCharacter("Boromir"));
// create some weapons (could be in a list too)
Weapon sword = new Weapon("Broadsword",40,5);
Weapon leatherShield = new Weapon("Leather Shield",2,35);
Weapon woodenStaff = new Weapon("Wooden Staff",30,10);
// and some food
Food bread = new Food("Bread", 15);
// because Weapons and food inherit from CollectableObject
// a player can carry either (polymorphism)
// equip the players
player[0].Add(sword);
player[0].Add(leatherShield);
player[1].Add(woodenStaff);
player[1].Add(bread);
// display the player we are viewing
DisplayPlayer(currentPlayerIndex);
}
// display info about a player by calling objects to string function
public void DisplayPlayer(int playerIndex)
{
// we number from 1 for the user
// try removing the brackets around playerIndex + 1 !!!
lblPlayerInfo.Text = "Player " + (playerIndex + 1);
PlayerCharacter pc = player[currentPlayerIndex];
txtPlayers.Text = pc.ToString();
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (currentPlayerIndex > 0)
{
currentPlayerIndex--;
DisplayPlayer(currentPlayerIndex);
}
}
private void btnNext_Click(object sender, EventArgs e)
{
if (currentPlayerIndex < player.Count)
{
currentPlayerIndex++;
DisplayPlayer(currentPlayerIndex);
}
}
}
}
最佳答案
您应该在递增/递减当前播放器索引之前仅显示播放器,或者将严格比较 (<) 替换为相等比较 (<=) :)
private void btnPrevious_Click(object sender, EventArgs e)
{
if (currentPlayerIndex >= 0)
{
currentPlayerIndex--;
DisplayPlayer(currentPlayerIndex);
}
}
private void btnNext_Click(object sender, EventArgs e)
{
if (currentPlayerIndex < player.Count)
{
currentPlayerIndex++;
DisplayPlayer(currentPlayerIndex);
}
}
关于c# - VS Breaking once 列表超过 2(1) 而不是循环回到 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40724194/