他のヒント

これがあなたが探しているものだと思います:

インデクサー(C#プログラミングガイド)

class SampleCollection<T>
{
    private T[] arr = new T[100];
    public T this[int i]
    {
        get
        {
            return arr[i];
        }
        set
        {
            arr[i] = value;
        }
    }
}

// This class shows how client code uses the indexer
class Program
{
    static void Main(string[] args)
    {
        SampleCollection<string> stringCollection = 
            new SampleCollection<string>();
        stringCollection[0] = "Hello, World";
        System.Console.WriteLine(stringCollection[0]);
    }
}

[]演算子はインデクサーと呼ばれます。整数、文字列、またはキーとして使用する他のタイプを取るインデクサーを提供できます。構文は、プロパティアクセサーと同じ原則に従って簡単です。

たとえば、 int がキーまたはインデックスである場合:

public int this[int index]
{
  get
  {
     return GetValue(index);
  }
}

インデクサーが読み取り専用ではなく読み取りおよび書き込みになるように、セットアクセサーを追加することもできます。

public int this[int index]
{
  get
  {
     return GetValue(index);
  }

  set
  {
    SetValue(index, value);
  }
}

異なるタイプを使用してインデックスを作成する場合は、インデクサーの署名を変更するだけです。

public int this[string index]
...
public int this[int index]
{
    get
    {
        return values[index];
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top