“Strange” C# property syntax

后端 未结 3 677
野趣味
野趣味 2020-11-28 16:29

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?

相关标签:
3条回答
  • 2020-11-28 17:07

    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")]
    
    0 讨论(0)
  • 2020-11-28 17:13

    this is called indexer.

    • Indexer
    • C++ implementation of the C# Property and Indexer with Accessor-Modifiers
    0 讨论(0)
  • 2020-11-28 17:16

    That's called an indexer. Read more about them at MSDN.

    0 讨论(0)
提交回复
热议问题