我是C#班的学生,这是我对课程的介绍,所以请耐心等待。按下“新建”按钮时,将使用名称和电话值创建CPerson对象,并且该对象将添加到“列表”<>中。
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
}
public partial class Form1 : Form
{
private List<CPerson> PhoneNum = new List<CPerson>(); //<CPerson> or <string>?
public Form1()
{
InitializeComponent();
newbutton.Enabled = false;
changebutton.Enabled = false;
savebutton.Enabled = false;
}
private void newbutton_Click(object sender, EventArgs e)
{
changebutton.Enabled = true;
savebutton.Enabled = true;
PhoneNum.Add(new CPerson { Name = Namebox.Text + " : ", Phone = phonebox.Text });
listBox1.Items.Add(PhoneNum); //text = "Collection"
}
作业说“CPerson ToString()覆盖将用于显示列表框中的名称和电话号码”,如上图所示,我不一定理解,但我猜我必须用这样的东西?
CPerson data = new CPerson();
data.ToString();
无论哪种方式,因为代码现在,我在列表框中得到的只是“(Collection)”。任何帮助将不胜感激!
答案 0 :(得分:2)
那就是要求覆盖ToString()方法。你可以这样做:
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
public override string ToString()
{
return Name + ": " + Phone;
}
我没有正确添加到列表中,但我假设您可以使用ToString()执行以下操作:
listBox1.Items.Add(data.ToString());
答案 1 :(得分:0)
...关闭
class CPerson
{
private string m_sName;
private string m_sPhone;
public string Name
{
get { return this.m_sName; }
set
{
this.m_sName = value;
}
}
public string Phone
{
get { return this.m_sPhone; }
set
{
this.m_sPhone = value;
}
}
public override string ToString()
{
return Name + ": " + Phone;
}
}
}