我创建了一个带派生类的基类。在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; }
}
答案 0 :(得分:0)
我想出了添加带有项目名称的对象作为对象属性的方法。它比我想象的要简单。首先,需要将相关属性(属性)声明为public。然后,使用以下代码设置列表框(与我自己的代码相关,如我的问题中所述):
PlayerListBox1.DisplayMember = "Name";
EnemyListBox1.DisplayMember = "Name";
这会将每个相应列表框的DisplayMember设置为类对象(实例)的“Name”属性。在原始问题的代码中,“Name”属性通过charName构造函数被下推到派生类。因此,派生类仍然以迂回的方式利用公共“名称”属性。