跳转至

0728 综合作业#

来源:D:\study\C#1\stu0728\0728作业

作业:索引器 — 员工信息管理#

class Employee
{
    // 两个字典分别存储 string→int 和 int→string 的映射
    Dictionary<string, int> employee = new Dictionary<string, int>();
    Dictionary<int, string> employees = new Dictionary<int, string>();

    private string Name { get; set; }
    private int Age { get; set; }

    // string 索引器 — 按姓名查找/设置年龄
    public int this[string name]
    {
        get { return employee[name]; }
        set { employee[name] = value; }
    }

    // int 索引器 — 按年龄查找/设置姓名
    public string this[int age]
    {
        get { return employees[age]; }
        set { employees[age] = value; }
    }
}

使用:

Employee employee = new Employee();
employee["hhhh"] = 123;    // 通过姓名设置年龄
Console.WriteLine(employee["hhhh"]);  // → 123

employee["aa"] = 25;       // 通过姓名设置年龄
Console.WriteLine(employee["aa"]);    // → 25

employee[23] = "Bob";      // 通过年龄设置姓名
Console.WriteLine(employee[23]);     // → "Bob"

要点:一个类可以定义多个索引器(索引器重载),只要参数列表不同即可。此例中 string 索引器用于"姓名→年龄"的映射,int 索引器用于"年龄→姓名"的映射。



相关笔记#