什么时候应该使用C#索引器? [英] When should you use C# indexers?

查看:283
本文介绍了什么时候应该使用C#索引器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更多地使用索引器,但是我不确定何时使用它们.我在网上找到的所有示例均使用诸如MyClassIndexerClass之类的类.

I'd like to use indexers more, but I'm not sure when to use them. All I've found online are examples that use classes like MyClass and IndexerClass.

在一个有学生和老师的学校系统中,每位老师都有他们负责的学生列表,在这种情况下需要索引器吗?为简单起见:每个学生只能属于一个老师.

What about in a school system where there are Students and Teachers, and each Teacher has a list of Students that they're in charge of - any need for indexers in that scenario? For simplicity's sake: each Student can only belong to one Teacher.

推荐答案

以下是我创建的视频 http://www.youtube.com/watch?v=HdtEQqu0yOY 及以下内容是对此的详细说明.

Heres a video i have created http://www.youtube.com/watch?v=HdtEQqu0yOY and below is a detailed explanation about the same.

索引器有助于使用简化的接口在类中访问包含的集合.这是一种语法糖.

Indexers helps to access contained collection with in a class using a simplified interface. It’s a syntactic sugar.

例如,假设您有一个内部包含地址集合的客户类.现在,我们想通过"Pincode"和"PhoneNumber"获取地址集合.因此,合乎逻辑的步骤是您将创建两个重载函数,一个重载函数通过"PhoneNumber"获取,另一个通过"PinCode"获取.您可以在下面的代码中看到我们定义了两个函数.

For instance lets say you have a customer class with addresses collection inside it. Now let’s say we would like to like fetch the addresses collection by "Pincode" and "PhoneNumber". So the logical step would be that you would go and create two overloaded functions one which fetches by using "PhoneNumber" and the other by "PinCode". You can see in the below code we have two functions defined.

Customer Customers = new Customer();
Customers.getAddress(1001);
Customers.getAddress("9090");

如果使用索引器,则可以使用以下代码中所示的内容简化上面的代码.

If you use indexer you can simplify the above code with something as shown in the below code.

Customer Customers = new Customer();
Address o = Customers[10001];
o = Customers["4320948"];

干杯.

这篇关于什么时候应该使用C#索引器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆