如何在c#.net中使用索引器? [英] how to use indexer in c#.net ?

查看:88
本文介绍了如何在c#.net中使用索引器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请给我c#.net中的索引器示例.

Please give me example of indexer in c#.net

推荐答案

索引器是一种特殊的属性类型,它允许类看起来像数组,即您可以使用方括号索引对其进行索引(因此得名).您一直在使用索引器-在List< T>中查找按索引,或按键的字典(或DataRows/Tables/etc).

在自定义类上需要索引器并不常见,因为框架提供的集合通常足够好,以至于当您需要类似行为的数组时,您可以使用一个(并且如果要转发列表到该类自己的索引器,您应该使用默认属性,尽管我不确定是否可以在C#中完成.

索引器的语法很简单:
An indexer is a special type of property that allows a class to appear like an array, i.e. you can index it (hence the name) with square bracket indexing. You use indexers all the time – looking up in a List<T> by index, or a Dictionary by key (or DataRows/Tables/etc).

It''s not that common to need an indexer on a custom class, because the collections provided by the framework are generally good enough that when you need something with array like behaviour you can use one (and if you want to forward a list to the class''s own indexer you should use the default property, though I''m not sure if that can be done in C#).

The syntax for an indexer is simple:
public int this[int index] {
 get { 
  // retrieve a value from somewhere
  return 42;
 }
 // optional
 set {
  // do something with the value and index
 }
}


这篇关于如何在c#.net中使用索引器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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