示例代码:
Employee.cs
using System;
class Employee
{
private string name;
private int age;
private int id;
public string Name
{
get { return this.name; }
set { this.name = value; }
}
public int Age
{
get { return this.age; }
set { this.age = value; }
}
public int ID
{
get { return this.id; }
}
public Employee(int id)
{
this.id = id;
}
public override string ToString()
{
return this.Name + ", " + this.Age + ", " + this.id;
}
}
Manager.cs
using System;
using System.Collections.Generic;
class Manager
{
private Dictionary<int, Employee> employees;
public Manager()
{
this.employees = new Dictionary<int, Employee>();
// initialize employees
Employee employee1 = new Employee(1001)
{
Name = "Owen",
Age = 22
};
Employee employee2 = new Employee(1002)
{
Name = "Vincent",
Age = 21
};
Employee employee3 = new Employee(1003)
{
Name = "Ricy",
Age = 20
};
// add employees to the dictionary
this.employees.Add(employee1.ID, employee1);
this.employees.Add(employee2.ID, employee2);
this.employees.Add(employee3.ID, employee3);
}
public Employee this[int id]
{
get
{
Employee employee = null;
this.employees.TryGetValue(id, out employee);
return employee;
}
set
{
if (value != null)
this.employees[id] = value;
}
}
public Employee this[string name]
{
get
{
var ems = this.employees.Values;
foreach(var em in ems)
{
if (em.Name.Equals(name))
return em;
}
return null;
}
}
}
Program.cs
using System;
class Program
{
public static void Main()
{
Manager manager = new Manager();
Console.WriteLine(manager[1001]);
Console.WriteLine(manager["Ricy"]);
Console.ReadLine();
}
}
运行结果: