c# - 比較演算子 - 演算子オーバーロード 利点
C#[duplicate]で[]演算子をどのようにオーバーロードしますか? (3)
[]演算子はインデクサと呼ばれます。 整数、文字列、またはキーとして使用するその他の型を取るインデクサを提供できます。 この構文は、プロパティアクセサーと同じ原則に従って簡単です。
たとえば、 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]
...
この質問には既に回答があります:
私はクラスに演算子を追加したいと思います。 私は現在、[]演算子で置き換えたいGetValue()メソッドを持っています。
class A
{
private List<int> values = new List<int>();
public int GetValue(int index)
{
return values[index];
}
}
私はこれがあなたが探しているものだと信じています:
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]);
}
}
public int this[int key]
{
get
{
return GetValue(key);
}
set
{
SetValue(key,value);
}
}