zoukankan      html  css  js  c++  java
  • 实现自定义的索引运算符

    自定义的索引运算符

    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);
        }
    }
  • 相关阅读:
    初识sql语句
    IO模型比较分析
    select,poll,epoll,selectors
    多路复用IO
    非阻塞IO
    yield-from示例
    阻塞IO(blocking IO)
    IO模型介绍
    gevent实现套接字
    gevent异步,io自动切换
  • 原文地址:https://www.cnblogs.com/singhwong/p/11930568.html
Copyright © 2011-2022 走看看