关闭

索引器

标签: c-sharp编程索引器
37人阅读 评论(0) 收藏 举报
分类:

示例代码:
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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:862次
    • 积分:161
    • 等级:
    • 排名:千里之外
    • 原创:16篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档