When should you use C# indexers?

后端 未结 10 1596
终归单人心
终归单人心 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条回答
  •  萌比男神i
    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;
            }
        }
    }
    

提交回复
热议问题