1 Star 0 Fork 0

徐艳玲 / ch4

Create your Gitee Account
Explore and code with more than 12 million developers,Free private repositories !:)
Sign up
This repository doesn't specify license. Please pay attention to the specific project description and its upstream code dependency when using it.
Clone or Download
top5.cs 2.09 KB
Copy Edit Raw Blame History
徐艳玲 authored 2023-10-18 18:16 . 添加项目文件。
/*假设我们有一个学生类(Student)和一个班级类(Class),我们想要实现能够按照学生姓名或者年龄进行索引访问班级中的学生。*/
using System;
using System.Collections.Generic;
// 学生类
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
// 班级类
public class Class
{
private Dictionary<string, Student> studentsByName;
private Dictionary<int, Student> studentsByAge;
public Class(List<Student> students)
{
studentsByName = new Dictionary<string, Student>();
studentsByAge = new Dictionary<int, Student>();
foreach (Student student in students)
{
studentsByName[student.Name] = student;
studentsByAge[student.Age] = student;
}
}
// 按姓名索引访问学生
public Student this[string name]
{
get
{
if (studentsByName.ContainsKey(name))
return studentsByName[name];
else
throw new KeyNotFoundException($"Student with name '{name}' not found in the class.");
}
}
// 按年龄索引访问学生
public Student this[int age]
{
get
{
if (studentsByAge.ContainsKey(age))
return studentsByAge[age];
else
throw new KeyNotFoundException($"Student with age '{age}' not found in the class.");
}
}
}
public class Program
{
public static void Main(string[] args)
{
// 创建学生对象
Student student1 = new Student { Name = "Alice", Age = 18 };
Student student2 = new Student { Name = "Bob", Age = 19 };
Student student3 = new Student { Name = "Charlie", Age = 17 };
// 创建班级对象,传入学生列表
Class classroom = new Class(new List<Student> { student1, student2, student3 });
// 按姓名索引访问学生
Console.WriteLine(classroom["Alice"].Age); // 输出:18
// 按年龄索引访问学生
Console.WriteLine(classroom[19].Name); // 输出:Bob
}
}
1
https://gitee.com/xu-yanling_989265/ch4.git
git@gitee.com:xu-yanling_989265/ch4.git
xu-yanling_989265
ch4
ch4
master

Search