设计一个windows应用程序,定义一个Student类,包含学号和姓名两个字段,并定义一个班级类ClassList,该类包含一个Student集合,使用索引器访问该集合。
(1)创建一个Windows应用程序Myproject6_1。
(2)设计界面,添加控件(输入框的那么属性分别为:txtsno、txtsname、txtIndex、txtdisplay,按钮的name属性分别为:btnAdd、btnLofoSno、btnLofoSna、btnLofoInd),如图所示。
(3)代码:
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 MyProject6_1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
ClassList clist = new ClassList(10); //创建一个容量为10的班级实例
int n = 0;
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtsno.Text.Trim() == "" || txtsname.Text.Trim() == "")
{
MessageBox.Show("请输入学生的学号或姓名!");
}
else
{
Student stu1 = new Student(txtsno.Text, txtsname.Text);
clist[n] = stu1;
n++;
txtdisplay.Text += string.Format("学号:{0},姓名:{1}",stu1.Sno,stu1.Sname )+"rn";
MessageBox.Show("添加成功!");
txtsno.Text = "";
txtsname.Text = "";
}
}
private void btnLofoInd_Click(object sender, EventArgs e)
{
try
{
if (txtIndex.Text == "")
{
MessageBox.Show("请输入索引号!");
}
else
{
Student stu1 = clist[Convert.ToInt32(txtIndex.Text)];
if (stu1 != null)
{
txtdisplay.Text = string.Format("学号:{0},姓名:{1}", stu1.Sno, stu1.Sname);
}
else
{
txtdisplay.Text = string.Format("没有索引值为a{0}的学生, Convert.ToInt32(txtIndex.Text));
}
}
}
catch {
MessageBox.Show("未找到学生信息!");
}
}
private void btnLofoSno_Click(object sender, EventArgs e)
{
try
{
if (txtsno.Text == "")
{
MessageBox.Show("请输入学号!");
}
else
{
Student stu1 = clist[txtsno .Text];
if (stu1 != null)
{
txtdisplay.Text = string.Format("学号:{0},姓名:{1}", stu1.Sno, stu1.Sname);
}
else
{
txtdisplay.Text = string.Format("没有找到学号是{0}的学生, txtsno.Text );
}
}
}
catch
{
MessageBox.Show("未找到学生信息!");
}
}
private void btnLofoSna_Click(object sender, EventArgs e)
{
try
{
if (txtsname.Text == "")
{
MessageBox.Show("请输入姓名!");
}
else
{
Student stu1 = clist[txtsname.Text];
if (stu1 != null)
{
txtdisplay.Text = string.Format("学号:{0},姓名:{1}", stu1.Sno, stu1.Sname);
}
else
{
txtdisplay.Text = string.Format("没有找到姓名是{0}的学生, txtsname.Text);
}
}
}
catch
{
MessageBox.Show("未找到学生信息!");
}
}
}
public class Student
{
private string sno;
private string sname;
public Student(string sno, string sname)
{
this.sno = sno;
this.sname = sname;
}
public string Sno
{
get
{
return sno;
}
}
public string Sname
{
get
{
return sname;
}
}
}
public class ClassList
{
private Student[] students;
public ClassList(int n)
{
students = new Student[n];
}
//根据索引查找
public Student this[int index]
{
get
{
if (index < 0 || index >= students.Length)
{
return null;
}
return students[index];
}
set
{
if (index < 0 || index >= students.Length)
{
return;
}
students[index] = value;
}
}
//按姓名或学号查找
public Student this[string infor]
{
get
{
foreach (Student stu in students)
{
if (stu.Sname == infor||stu.Sno==infor)
{
return stu;
}
}
return null;
}
}
}
}
(4)运行结果:
添加学生:
按索引查找,如果超出则为:
按姓名查找:
按学号查找:



