索引器

示例代码:
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();
        }
    }

运行结果:
运行结果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值