• 实现自定义的索引运算符


    自定义的索引运算符

    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);
        }
    }
  • 相关阅读:
    DEDE调用当前文档中TAG标签利于内页优化提高收录量
    DEDE搜索结果将按点击排序展现方式的修改方法
    win 03 系统 IIS无法解析PHP之解决办法
    【原创】广告调用类,支持Flash调用
    中英文语言转换类
    PHP 获取内网用户MAC地址(WINDOWS/linux)解决方案
    DEDE删除文章怎么同时也删除附件,DEDE删除文章同时删除附件
    windows 2003下配置php环境
    When is a Test not a Unit Test?
    IBM WebSphere Commerce Front_dev
  • 原文地址:https://www.cnblogs.com/singhwong/p/11930568.html
Copyright © 2020-2023  润新知