1、里面运用到了IEnumerable<>接口,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
public class Persen
{
public DateTime Birther { get; }
public string FirstName { get; }
public string LastName { get; }
public Persen(string FirstName,string LastName,DateTime Birther)
{
this.Birther = Birther;
this.FirstName = FirstName;
this.LastName = LastName;
}
}
public class PersenCollection
{
private Persen[] _People;
public PersenCollection(params Persen[] people)
{
_People = people.ToArray();
}
public Persen this[int indxe] // int 索引
{
get
{
return _People[indxe];
}
set
{
_People[indxe] = value;
}
}
public IEnumerable<Persen> this[DateTime birthDay] // 自定义索引 返回一个Persen对象列表
{
get
{
return _People.Where(p => p.Birther == birthDay);
}
}
}
class Program
{
static void Main(string[] args)
{
var p1 = new Persen("111", "aaa", new DateTime(1960, 3, 2));
var p2 = new Persen("222", "bbb", new DateTime(1999, 3, 5));
var p3 = new Persen("333", "ccc", new DateTime(1999, 3, 6));
var p4 = new Persen("444", "ddd", new DateTime(1960, 3, 2));
var coll = new PersenCollection(p1, p2, p3, p4);
Console.WriteLine($"{coll[2].FirstName} {coll[2].LastName} {coll[2].Birther}");
foreach (var p in coll[new DateTime(1960,3,2)]) // coll[new DateTime(1960,3,2)] 利用索引返回了一个 生日为1960.3.2的person对象列表。
{
Console.WriteLine($"{p.FirstName} {p.LastName} {p.Birther}");
}
Console.WriteLine();
}
}
}
2、其实用list<> 存 Person对象 也可以的。