Come posso sovraccaricare l'operatore [] in C # [duplicato]
-
05-07-2019 - |
Domanda
Questa domanda ha già una risposta qui:
Vorrei aggiungere un operatore a una classe. Al momento ho un metodo GetValue ()
che vorrei sostituire con un operatore []
.
class A
{
private List<int> values = new List<int>();
public int GetValue(int index)
{
return values[index];
}
}
Soluzione
public int this[int key]
{
get
{
return GetValue(key);
}
set
{
SetValue(key,value);
}
}
Altri suggerimenti
Credo che questo sia quello che stai cercando:
Indicizzatori (Guida per programmatori 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]);
}
}
L'operatore [] è chiamato indicizzatore. Puoi fornire indicizzatori che accettano un numero intero, una stringa o qualsiasi altro tipo che desideri utilizzare come chiave. La sintassi è semplice, seguendo gli stessi principi degli accessori di proprietà.
Ad esempio, nel tuo caso in cui un int
è la chiave o l'indice:
public int this[int index]
{
get
{
return GetValue(index);
}
}
Puoi anche aggiungere un set accessor in modo che l'indicizzatore diventi in lettura e scrittura anziché in sola lettura.
public int this[int index]
{
get
{
return GetValue(index);
}
set
{
SetValue(index, value);
}
}
Se vuoi indicizzare usando un tipo diverso, devi semplicemente cambiare la firma dell'indicizzatore.
public int this[string index]
...
public int this[int index]
{
get
{
return values[index];
}
}