实现自定义的索引运算符

自定义的索引运算符

using System;
using System.Collections.Generic;
using System.Linq;

namespace 实现自定义的索引运算符
{
    class Program
    {
        static void Main(string[] args)
        {
            //Console.WriteLine("Hello World!");
            var p1 = new Person("Ayrton","Senna",new DateTime(1960,3,21));
            var p2 = new Person("Ronnie","Peterson",new DateTime(1944,2,14));
            var p3 = new Person("Jochen","Rindt",new DateTime(1942,4,18));
            var p4 = new Person("Francois","Cevert",new DateTime(1944,2,25));
            var coll = new  PersonCollection(p1,p2,p3,p4);
            System.Console.WriteLine(coll[2]);
            foreach(var r in coll[new DateTime(1960,3,21)]){
                System.Console.WriteLine(r);

            }
            System.Console.ReadLine();

            //输出结果如下
            // Jochen Rindt
            // Ayrton Senna
        }
    }

    public class Person
    {
        public DateTime Birthday{get;}
        public string FirstName{get;}
        public string LastName{get;}

        public Person(string firstName,string lastName,DateTime birthday){
            FirstName = firstName;
            LastName = lastName;
            Birthday = birthday;

        }

        public override string ToString()=>$"{FirstName} {LastName}";
    }

    public class PersonCollection
    {
        private Person[] _people;
        public PersonCollection(params Person[] people)=>_people = people.ToArray(); 
        //为了允许使用索引器语法访问PersonCollection并返回Person对象,可以创建一个索引器。
        public Person this[int index]
        {
            //检索值时调用get访问器,在右边传递Person对象时调用set访问器。
            get=>_people[index];
            set=>_people[index] = value;
        }

        //这个索引器用来返回有指定生日的每个人,因为同一个生日可能有多人,所以使用接口
        //IEnumerable<Person>返回一个Person对象列表。
        // public IEnumerable<Person> this[DateTime birthday]
        // {
        //     get=>_people.Where(p=>p.Birthday == birthday);
        // }
        public IEnumerable<Person> this[DateTime birthday]=>_people.Where(p=>p.Birthday == birthday);
    }
}

 

posted @ 2019-11-25 21:11  singhwong  阅读(257)  评论(0编辑  收藏  举报