C#是什么一个索引点或利益? [英] C# what is the point or benefit of an indexer?

查看:120
本文介绍了C#是什么一个索引点或利益?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

做一些读码和在这个片段中跌跌撞撞,我没有见过的:

Doing some code reading and stumbled upon this snippet that I haven't seen before:

public SomeClass {
  public someInterface this[String strParameter] {
    get {
      return SomeInternalMethod(strParameter);
    }
  }
}



它看起来像它被称为如下:

It looks like it is called as follows:

SomeClass _someClass = new SomeClass();
SomeInterface returnedValue = _someClass["someString"];



我有兴趣在此功能将是合适的还是什么写这种风格的意图。 ?例如,为什么会变成这样优于简单地调用该函数

I am interested in where this function would be appropriate or what the intent of writing in this style. For example why would this be preferred over simply calling the function?

推荐答案

请参阅语言规范,10.9节,其中规定:

See the language specification, section 10.9, which states:

这是 索引 是使以同样的方式作为数组要索引的对象的成员。

An Indexer is a member that enables an object to be indexed in the same way as an array.

索引器和属性在概念上非常相似,但在以下方面有所不同:

Indexers and properties are very similar in concept, but differ in the following ways:


  • 属性是由它的名称标识,而索引是由它的签名标识。

  • 的属性是通过简单名称访问(第7.5.2节)或成员 - 访问(第7.5.4节),而索引元素通过元素访问访问(第7.5.6.2节)。

  • 系统属性可以是static成员,而索引始终是一个实例成员。

  • 属性的get访问对应于不带参数的方法,而索引的get访问对应于具有相同的形式参数列表索引的方法。

  • 属性的set访问对应于具有名为value的单个参数的方法,而索引的set访问对应于具有相同的形式参数列表索引的方法,加附加参数指定值。

  • 这是一个索引访问来声明一个局部变量具有相同的名称作为索引参数编译时错误。

  • 在压倒一切的财产申报,继承属性是使用语法base.P,其中P为属性名称访问。在压倒一切的索引器声明,继承的索引器是使用语法基础[E],其中E是一个逗号分隔的表达式列表访问。

  • A property is identified by its name, whereas an indexer is identified by its signature.
  • A property is accessed through a simple-name (§7.5.2) or a member-access (§7.5.4), whereas an indexer element is accessed through an element-access (§7.5.6.2).
  • A property can be a static member, whereas an indexer is always an instance member.
  • A get accessor of a property corresponds to a method with no parameters, whereas a get accessor of an indexer corresponds to a method with the same formal parameter list as the indexer.
  • A set accessor of a property corresponds to a method with a single parameter named value, whereas a set accessor of an indexer corresponds to a method with the same formal parameter list as the indexer, plus an additional parameter named value.
  • It is a compile-time error for an indexer accessor to declare a local variable with the same name as an indexer parameter.
  • In an overriding property declaration, the inherited property is accessed using the syntax base.P, where P is the property name. In an overriding indexer declaration, the inherited indexer is accessed using the syntax base[E], where E is a comma separated list of expressions.

这篇关于C#是什么一个索引点或利益?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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