关于自定义索引运算符

使用[]来索引,一般填写的都是int数字,但是其实我们可以自定义,括号中可以填写其他的内容。主要使用了this关键词和**[]**运算符。

主要看PersonCollection里面的代码

Person

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}";
}

PersonCollection

public class PersonCollection
{
    private Person[] _people;

    public PersonCollection(params Person[] people) =>
        _people = people.ToArray();

    //常见的int索引
    public Person this[int index]
    {
        get => _people[index];
        set => _people[index] = value;
    }
    //自定义的根据日期的索引
    public Person this[DateTime birthDay] => _people.Where(p => p.Birthday == birthDay).First();

    //public IEnumerable<Person> this[DateTime birthDay] => _people.Where(p => p.Birthday == birthDay);
}

Main方法中,我们分别使用int和DateTime的两种索引方式

static void Main()
{
    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);

    Console.WriteLine(coll[2]);

    Console.WriteLine(coll[new DateTime(1960, 3, 21)]);
    Console.ReadLine();
}

···输出
Jochen Rindt
Ayrton Senna   

总结

似乎没什么用,和查找有点点像,但是index似乎就是索引……

我也有点点糊涂了