When should you use C# indexers?

后端 未结 10 1560
终归单人心
终归单人心 2020-12-06 10:10

I\'d like to use indexers more, but I\'m not sure when to use them. All I\'ve found online are examples that use classes like MyClass and IndexerClass

相关标签:
10条回答
  • 2020-12-06 10:34

    The simple answer (as stated above) is when the class represents/contains a collection of items, the indexer will return the elements of the collection.

    public Student this[int index] { ..
    

    In a more advanced case you can create a default behavior with a class and make it look a bit like a delegate, especially when the class represents a mapping, or a process. For example a class that calculates the cooling rate of a beer in the refrigerator:

    Instead of typing

    temperature = coorsLight.CalculateFutureTemperature(time);
    

    you can condence this to

    temperature = coorsLight[time];
    

    if the expected behavior (and intent) of the class is to return a value.

    0 讨论(0)
  • 2020-12-06 10:38

    Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

    Indexers enable objects to be indexed in a similar manner to arrays.

        // C#: INDEXER 
    using System; 
    using System.Collections; 
    
    class MyClass 
    { 
        private string []data = new string[5]; 
        public string this [int index] 
        { 
           get 
           { 
               return data[index]; 
           } 
           set 
           { 
               data[index] = value; 
           } 
        } 
    }
    
    class MyClient 
    { 
       public static void Main() 
       { 
          MyClass mc = new MyClass(); 
          mc[0] = "Rajesh"; 
          mc[1] = "A3-126"; 
          mc[2] = "Snehadara"; 
          mc[3] = "Irla"; 
          mc[4] = "Mumbai"; 
          Console.WriteLine("{0},{1},{2},{3},{4}",mc[0],mc[1],mc[2],mc[3],mc[4]); 
       } 
    } 
    

    Code project

    0 讨论(0)
  • 2020-12-06 10:41

    Indexer is a highly specialized property which allows instances of a class (or struct) to be indexed just like an array(properties can be static but indexers cannot).

    Why use indexers:
    - instead of a new data structure, the class itself is a data structure.
    - simplified syntax - syntactic sugar

    When to use:
    - if your class needs list(/array) of its instances (example 1)
    - if your class represents list(/array) of values directly related to your class (example 2)

    Example 1:

    public class Person{
        public string Name{get; set;}
    
        private Person[] _backingStore;
        public Person this[int index]
        {
            get{
                return _backingStore[index];
            }
            set{
                _backingStore[index] = value;
            }
        }
    }
    
    Person p = new Person();
    p[0] = new Person(){Name = "Hassan"};
    p[1] = new Person(){Name = "John Skeet"};    
    

    Example 2:

    class TempratureRecord{
        private float[] temps = new float[10] { 56.2F, 56.7F, 56.5F, 56.9F, 58.8F, 61.3F, 56.5F, 56.9F, 58.8F, 61.3F};
    
        public int Length{
            get { return temps.Length; }
        }
    
        public float this[int index]
        {
            get{
                return temps[index];
            }
            set{
                temps[index] = value;
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-06 10:43

    Random order access

    You would use an enumerator if your data is normally accessed sequentially.

    An indexer on the other hand is useful for directly accessing a specific element, no specific order.

    This of course assumes you know the index of the element you want. Comboboxes for example have always supported two values: the string shown to the user, and the id that belongs with it. You could use the id from a selected item in a combobox to directly access the index of your collection, instead of having to search the collection.

    The nice thing about indexers in C# is that you can overload them, so you can access items through different kind of keys.

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