備忘録

政治/経済/自動運転/Python/Robotics

Overloaded Operator, Indexer, Property

メモ

  • 代入演算子オーバーロードできない
  • get, set←value
  • indexer, propertyは記憶領域をもたないため、参照で渡せない
  • accessorに修飾子をつけてよい
  • 自動実装するproperty:: public int UserCount {get; set; }

 

<Indexer>

class SampleCollection<T>
{
    // Declare an array to store the data elements.
    private T[] arr = new T[100];

    // Define the indexer, which will allow client code
    // to use [] notation on the class instance itself.    
    public T this[int i]
    {
        get
        {
            // This indexer is very simple, and just returns or sets
            // the corresponding element from the internal array.
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

<Property>

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}