C#创建一个教师类Teacher,具有姓名、专业、年龄等属性。使用泛型集合Dictionary<Tkey,Tvalue>存储几个教师对象,实现教师对象信息的增删改查。
时间: 2024-11-03 20:19:06 浏览: 41
C#泛型集合Dictionary<K,V>的使用方法
在C#中,你可以创建一个名为`Teacher`的类来表示教师,包含基本的属性如姓名(Name)、专业(Specialty)和年龄(Age)。接下来,我们将使用泛型集合`Dictionary<TKey, TValue>`来存储这些教师对象,其中`TKey`通常用于索引,这里可以是整数或其他唯一标识符,`TValue`就是我们的`Teacher`对象。
首先,定义`Teacher`类:
```csharp
public class Teacher
{
public string Name { get; set; }
public string Specialty { get; set; }
public int Age { get; set; }
// 构造函数
public Teacher(string name, string specialty, int age)
{
Name = name;
Specialty = specialty;
Age = age;
}
}
```
然后,创建一个泛型字典`TeachersDict`来存储教师对象:
```csharp
Dictionary<int, Teacher> TeachersDict = new Dictionary<int, Teacher>();
```
接下来,我们实现添加、删除、修改和查询教师的功能:
**添加教师(Add)**:
```csharp
public void AddTeacher(Teacher teacher)
{
if (!TeachersDict.ContainsKey(teacher.Id))
{
TeachersDict.Add(teacher.Id, teacher);
Console.WriteLine($"添加了教师: {teacher.Name}");
}
else
{
Console.WriteLine("教师已存在,无法添加");
}
}
```
**删除教师(Remove)**:
```csharp
public void RemoveTeacher(int id)
{
if (TeachersDict.ContainsKey(id))
{
TeachersDict.Remove(id);
Console.WriteLine($"删除了教师: {GetTeacherById(id).Name}");
}
else
{
Console.WriteLine("找不到该教师");
}
}
private Teacher GetTeacherById(int id) => TeachersDict[id];
```
**修改教师(Update)**:
```csharp
public void UpdateTeacher(int id, Teacher updatedTeacher)
{
if (TeachersDict.ContainsKey(id))
{
TeachersDict[id] = updatedTeacher;
Console.WriteLine($"更新了教师: {updatedTeacher.Name} 的信息");
}
else
{
Console.WriteLine("找不到该教师");
}
}
```
**查询教师(Find or Search)**:
```csharp
public Teacher FindTeacher(int id)
{
return TeachersDict.ContainsKey(id) ? TeachersDict[id] : null;
}
```
阅读全文