尝试循环浏览我的角色,但是当我在最后一个角色点击下一个时,它会中断。 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);
}
}
}
}
答案 0 :(得分:0)
您应该在递增/递减currentPlayerIndex之前使用DisplayPlayer,或者通过与等式(&lt; =)进行比较来替换严格比较(&lt;)。)
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);
}
}