将数组对象的参数输出为字符串
本文关键字:输出 字符串 参数 数组 对象 | 更新日期: 2023-09-27 18:37:27
我有以下代码:
public partial class Form1 : Form
{
const int MaxStudents = 4;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Student[] studentList;
studentList = new Student[4];
studentList[0] = new Student(51584, 17);
studentList[1] = new Student(51585, 19);
studentList[2] = new Student(51586, 15);
studentList[3] = new Student(51587, 20);
for (int i = 0; i < MaxStudents; i++)
{
lstStudents.Items.Add(studentList.ToString()[i]);
}
}
编辑:在学生班中,我有:
public Student(int id, int age) {
this.id = id;
this.age = age;
}
public override string ToString()
{
return string.Format("ID: {0} - Age: {1}", this.id, this.age);
}
然后以我的形式加载:
private void Form1_Load(object sender, EventArgs e)
{
Student[] studentList;
studentList = new Student[4];
studentList[0] = new Student(51584, 17);
studentList[1] = new Student(51585, 19);
studentList[2] = new Student(51586, 15);
studentList[3] = new Student(51587, 20);
lstStudents.Items.AddRange(studentList);
}
我想知道如何将数组中每个对象的参数输出到列表框。我将如何使每个对象都像这样显示在列表框中:
编号: 51584 - 年龄: 17
我不太确定如何将参数转换为要在列表框中列出的纯文本,同时在参数之前添加其他文本(就像我对"id:",连字符和"年龄:"所做的那样)
很抱歉这个冗长的问题,但我想我会尽我所能解释。
如果您希望在需要字符串值时随时以这种方式显示Student
,最简单的方法是覆盖ToString
:
public override string ToString()
{
return string.Format("Name: {0} - Age: {1}", this.Name, this.Age);
}
然后你可以做
lstStudents.Items.Add(studentList[i]);
添加对象而不是字符串的好处是,列表框的 SelectedItem
属性将是对象,而不仅仅是字符串表示形式。
或者,您可以设置发送到列表框的字符串的格式:
lstStudents.Items.Add(string.Format("Name: {0} - Age: {1}", studentList[i].Name, studentList[i].Age));
仔细看看这一行:
lstStudents.Items.Add(studentList.ToString()[i]);
你写studentList.ToString()[i]
.这意味着您拨打ToString
studentList
而不是学生。它应该是lstStudents.Items.Add(studentList[i].ToString())
的(索引器[i]
放在studentList
后面)。
假设您覆盖了Student
类中的ToString
,您可以在一次调用中添加所有学生:
private void Form1_Load(object sender, EventArgs e)
{
Student[] studentList;
studentList = new Student[4];
studentList[0] = new Student(51584, 17);
studentList[1] = new Student(51585, 19);
studentList[2] = new Student(51586, 15);
studentList[3] = new Student(51587, 20);
lstStudents.Items.AddRange(studentList);
}
// Class student - create property
public string Display
{
get { return string.Format("ID: {0} - Age: {1}", this.ID, this.Age); }
}
// In the form class - set listbox
lstStudents.Datasource = StudentArray;
lstStudents.DisplayMember = "Display";
lstStudents.ValueMember = "ID";
// The benefit of this is that later you can do this
Student s = (Student)lstStudents.SelectedItem
// Now you have access to full student info