Fetch the repository succeeded.
/*假设我们有一个学生类(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
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。