Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
479 views
in Technique[技术] by (71.8m points)

methods - C# what is the point or benefit of an indexer?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

  • 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...