Indexer-Syntax index用法

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • https://blog.csdn.net/u011185231/article/details/51591571...
    燕京博士阅读 671评论 0 0
  • 花 可以娇艳 但香气不可以太浓郁 有时浓郁的香气让人窒息 人 可以自信 但为人不可以太骄傲 有时骄傲的人让人鄙夷 ...
    潋滟波光阅读 155评论 0 2
  • “虽然心里诸多烦恼,还是得去上班啊。”一边开着车,晓静烦躁得自言自语。 “咦,那是什么?怎么感觉在和我说话呢?”晓...
    瑾瑜的童话阅读 347评论 0 2
  • 2017.11.10 周五 高畅 双十一的晚上,感性消费剁手前,先理性思考一下,到底我们是在为什么买单。 你想...
    畅_759c阅读 233评论 0 0
  • 我以前,看到一对小情侣在我面前含笑倩然,会心里翻个白眼儿,肉麻!现在,再看这样一对,心里却只剩艳羡! 要不怎么说,...
    格蕾丝高grace阅读 242评论 0 0