Indexer-Syntax index用法

2019-02-14  本文已影响0人  津涵

Person.cs

1.png

PersonCollection.cs

2.png

代码解析:

(1)index 数组下标
For allowing indexer-syntax to be used to access the PersonCollection and return Person objects, you can create an indexer. The indexer looks very similar to a property as it also contains get and set accessors. What’s different is the name. Specifying an indexer makes use of the this keyword. The brackets that follow the this keyword specify the type that is used with the index. An array offers indexers with the int type, so int types are here used as well to pass the information directly to the contained array _people. The use of the set and get accessors is very similar to properties. The get accessor is invoked when a value is retrieved, the set accessor when a (Person object) is passed on the right side.
coding:
public Person this[int index]
{
get => _people[index];
set => _people[index] = value;
}

(2)index 其它类型变量
With indexers, you cannot only define int types as the indexing type. Any type works, as is shown here with the DateTime struct as indexing type. This indexer is used to return every person with a specified birthday. Because multiple persons can have the same birthday, not a single Person object is returned but a list of persons with the interface IEnumerable<Person>. The Where method used makes the filtering based on a lambda expression.
coding:
public IEnumerable<Person> this[DateTime birthDay]
{
get => _people.Where(p => p.Birthday == birthDay);
}
改:
The indexer using the DateTime type offers retrieving person objects, but doesn’t allow you to set person objects as there’s only a get accessor but no set accessor. A shorthand notation exists to create the same code with an expression-bodied member.
coding:
public IEnumerable<Person> this[DateTime birthDay] =>
_people.Where(p => p.Birthday == birthDay);

Main.cs

3.png
上一篇下一篇

猜你喜欢

热点阅读