正在将对象添加到具有name属性的列表框中
本文关键字:属性 name 列表 对象 添加 | 更新日期: 2023-09-27 18:25:35
我创建了一个带有派生类的基类。在winforms中,在相对类中添加了类的属性后,应该将派生类的实例添加到列表框中,并使用派生类的name属性作为列表框中的项名称。我收到一个OutOfMemory异常,表示列表框已满。列表框中没有项目,所以我的代码不知怎么陷入了添加项目的循环中。以下是派生类的相关代码片段:
//child class
public class Player : Character
{
//new attributes
string gender;
bool dead;
//constructor
public Player(string charName, int charHitPoints, int charAC, int charAttack, int charDamage, string charAttackType, string Gender, bool Dead)
: base(charName, charHitPoints, charAC, charAttack, charDamage, charAttackType)
{
gender = Gender;
dead = Dead;
}
//accessible attributes
public string PlayerGender { get; set; }
public bool PlayerDead { get; set; }
public override string ToString()
{
return Name;
}
}
正如您所看到的,我正在尝试使用Name属性作为列表框中的项目名称。也许我没有正确使用覆盖?这是用于向列表框中添加实例的相关代码片段。这发生在winforms按钮的点击事件上:
//create button
private void button1_Click(object sender, EventArgs e)
{
//if creating a Player
if (radioButton1.Checked & !radioButton2.Checked)
{
int value1;
if (int.TryParse(textBox2.Text, out value1)
&& int.TryParse(textBox3.Text, out value1)
&& int.TryParse(textBox4.Text, out value1)
&& int.TryParse(textBox5.Text, out value1))
{
//create new object of Player class
PlayerListBox1.Items.Add (new Player(textBox1.Text, Convert.ToInt32(textBox2.Text), Convert.ToInt32(textBox3.Text), Convert.ToInt32(textBox4.Text), Convert.ToInt32(textBox5.Text), textBox6.Text, textBox7.Text, false));
}
else
{
MessageBox.Show("Please enter only numbers for Hit Points, Armor Class, Attack, and Damage.", "Invalid Input");
}
}
}
谢谢你的帮助!
更新:这是基类:
//parent class
public class Character
{
//common attributes
string name;
int hitPoints;
int armorClass;
int attack;
int damage;
string attackType;
//constructor
public Character(string charName, int charHitPoints, int charAC, int charAttack, int charDamage, string charAttackType)
{
//constructor arguments
name = charName;
hitPoints = charHitPoints;
armorClass = charAC;
attack = charAttack;
damage = charDamage;
attackType = charAttackType;
}
//accessible attributes
public string Name{get; set;}
public int HitPoints { get; set; }
public int ArmorClass { get; set; }
public int Attack { get; set; }
public int Damage { get; set; }
public string AttackType { get; set; }
}
我找到了添加一个以项名称作为对象属性的对象的方法。这比我想象的要简单。首先,需要将相关属性(属性)声明为公共属性。然后,列表框设置有以下代码(与我自己的代码相关,如我的问题中所述):
PlayerListBox1.DisplayMember = "Name";
EnemyListBox1.DisplayMember = "Name";
这将把每个列表框的DisplayMember设置为类对象(实例)的"Name"属性。在我最初问题的代码中,"Name"属性是通过charName构造函数向下推送到派生类的。因此,派生类仍然以迂回的方式使用公共的"Name"属性。