c#创建一个学生类Student,具有姓名、学号、年龄、班级等属性。使用泛型集合List<T>存储几个学生对象,实现学生对象信息的增删查。各项操作要有提示信息。
时间: 2024-11-03 09:17:57 浏览: 79
在C#中,我们可以创建一个名为`Student`的类,包含一些基本的学生属性。这里是一个简单的例子:
```csharp
public class Student
{
public string Name { get; set; }
public int StudentID { get; set; }
public int Age { get; set; }
public string ClassName { get; set; }
// 构造函数
public Student(string name, int studentID, int age, string className)
{
Name = name;
StudentID = studentID;
Age = age;
ClassName = className;
}
}
// 创建一个泛型集合 List<Student>
public static class StudentCollection<T> where T : Student
{
private List<T> students = new List<T>();
// 添加学生
public void AddStudent(T student)
{
Console.WriteLine("添加学生...");
students.Add(student);
}
// 删除学生(通过学号)
public void RemoveStudentByStudentID(int id)
{
Console.WriteLine("删除学号为" + id + "的学生...");
students.RemoveAll(s => s.StudentID == id);
}
// 查询学生(通过姓名)
public T FindStudentByName(string name)
{
Console.WriteLine("查找名字为" + name + "的学生...");
return students.Find(student => student.Name == name);
}
}
```
你可以这样使用这个类:
```csharp
Student student1 = new Student("张三", 1001, 18, "一班");
Student student2 = new Student("李四", 1002, 19, "二班");
StudentCollection<Student> studentCollection = new StudentCollection<Student>();
studentCollection.AddStudent(student1);
studentCollection.AddStudent(student2);
// 查找并打印张三的信息
var foundStudent = studentCollection.FindStudentByName("张三");
if (foundStudent != null)
{
Console.WriteLine(foundStudent.Name + " 的详细信息...");
}
else
{
Console.WriteLine("未找到该学生。");
}
// 删除学号为1001的学生
studentCollection.RemoveStudentByStudentID(1001);
```
阅读全文