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
555 views
in Technique[技术] by (71.8m points)

properties - “Strange” C# property syntax

I just saw this in a c# project:

public char this[int index]

I consider myself new to C#; any one can help what it's meaning?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It is an Indexer.

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters. An indexer provides array-like syntax. It allows a type to be accessed the same way as an array. Properties such as indexers often access a backing store. We often accept a parameter of int type and access a backing store of array type.

Read it from http://www.dotnetperls.com/indexer

string s = "hello";
Console.WriteLine (s[0]); // 'h'
Console.WriteLine (s[3]); // 'l'

Implementing an indexer

To write an indexer, define a property called this, specifying the arguments in square brackets. For instance:

class Sentence
{
   string[] words = "The quick brown fox".Split();
   public string this [int wordNum] // indexer
   {
      get { return words [wordNum]; }
      set { words [wordNum] = value; }
   }
}

Here’s how we could use this indexer:

Sentence s = new Sentence();
Console.WriteLine (s[3]); // fox
s[3] = "kangaroo";
Console.WriteLine (s[3]); // kangaroo

A type may declare multiple indexers, each with parameters of different types. An indexer can also take more than one parameter:

public string this [int arg1, string arg2]
{
  get  { ... } set { ... }
}

Indexers internally compile to methods called get_Item and set_Item, as follows:

public string get_Item (int wordNum) {...}
public void set_Item (int wordNum, string value) {...}

The compiler chooses the name Item by default—you can actually change this by decorating your indexer with the following attribute:

[System.Runtime.CompilerServices.IndexerName ("Blah")]

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

2.1m questions

2.1m answers

60 comments

57.0k users

...