Indexadores (Guia de Programação em C#)Indexers (C# Programming Guide)
Os indexadores permitem que instâncias de uma classe ou struct sejam indexados como matrizes.Indexers allow instances of a class or struct to be indexed just like arrays. O valor indexado pode ser definido ou recuperado sem especificar explicitamente um membro de instância ou tipo.The indexed value can be set or retrieved without explicitly specifying a type or instance member. Os indexadores parecem com propriedades, a diferença é que seus acessadores usam parâmetros.Indexers resemble properties except that their accessors take parameters.
O exemplo a seguir define uma classe genérica com métodos de acesso get e set simples para atribuir e recuperar valores.The following example defines a generic class with simple get and set accessor methods to assign and retrieve values. A classe Program
cria uma instância dessa classe para armazenar cadeias de caracteres.The Program
class creates an instance of this class for storing strings.
using System;
class SampleCollection<T>
{
// Declare an array to store the data elements.
private T[] arr = new T[100];
// Define the indexer to allow client code to use [] notation.
public T this[int i]
{
get { return arr[i]; }
set { arr[i] = value; }
}
}
class Program
{
static void Main()
{
var stringCollection = new SampleCollection<string>();
stringCollection[0] = "Hello, World";
Console.WriteLine(stringCollection[0]);
}
}
// The example displays the following output:
// Hello, World.
Observação
Para mais exemplos, consulte as seções relacionadas.For more examples, see Related Sections.
Definições de corpo de expressãoExpression Body Definitions
É comum para um acessador get ou set de um indexador ser constituído de uma única instrução que retorna ou define um valor.It is common for an indexer's get or set accessor to consist of a single statement that either returns or sets a value. Os membros de expressão fornecem uma sintaxe simplificada para dar suporte a esse cenário.Expression-bodied members provide a simplified syntax to support this scenario. Começando do C# 6, um indexador somente leitura pode ser implementado como um membro de expressão, como mostra o exemplo a seguir.Starting with C# 6, a read-only indexer can be implemented as an expression-bodied member, as the following example shows.
using System;
class SampleCollection<T>
{
// Declare an array to store the data elements.
private T[] arr = new T[100];
int nextIndex = 0;
// Define the indexer to allow client code to use [] notation.
public T this[int i] => arr[i];
public void Add(T value)
{
if (nextIndex >= arr.Length)
throw new IndexOutOfRangeException($"The collection can hold only {arr.Length} elements.");
arr[nextIndex++] = value;
}
}
class Program
{
static void Main()
{
var stringCollection = new SampleCollection<string>();
stringCollection.Add("Hello, World");
System.Console.WriteLine(stringCollection[0]);
}
}
// The example displays the following output:
// Hello, World.
Observe que =>
apresenta o corpo da expressão e que a palavra-chave get
não é usada.Note that =>
introduces the expression body, and that the get
keyword is not used.
Começando do C# 7.0, os acessadores get e set podem ser implementados como membros aptos para expressão.Starting with C# 7.0, both the get and set accessor can be an implemented as expression-bodied members. Nesse caso, as palavras-chave get
e set
devem ser usadas.In this case, both get
and set
keywords must be used. Por exemplo:For example:
using System;
class SampleCollection<T>
{
// Declare an array to store the data elements.
private T[] arr = new T[100];
// Define the indexer to allow client code to use [] notation.
public T this[int i]
{
get => arr[i];
set => arr[i] = value;
}
}
class Program
{
static void Main()
{
var stringCollection = new SampleCollection<string>();
stringCollection[0] = "Hello, World.";
Console.WriteLine(stringCollection[0]);
}
}
// The example displays the following output:
// Hello, World.
Visão Geral dos IndexadoresIndexers Overview
Os indexadores permitem que objetos sejam indexados de maneira semelhante às matrizes.Indexers enable objects to be indexed in a similar manner to arrays.
Um acessador
get
retorna um valor.Aget
accessor returns a value. Um acessadorset
atribui um valor.Aset
accessor assigns a value.A palavra-chave this é usada para definir o indexador.The this keyword is used to define the indexer.
A palavra-chave value é usada para definir o valor que está sendo atribuído pelo acessador
set
.The value keyword is used to define the value being assigned by theset
accessor.Os indexadores não precisam ser indexados por um valor inteiro. Você deve definir o mecanismo de pesquisa específico.Indexers do not have to be indexed by an integer value; it is up to you how to define the specific look-up mechanism.
Os indexadores podem ser sobrecarregados.Indexers can be overloaded.
Os indexadores podem ter mais de um parâmetro formal, por exemplo, ao acessar uma matriz bidimensional.Indexers can have more than one formal parameter, for example, when accessing a two-dimensional array.
Seções relacionadasRelated Sections
Comparação entre propriedades e indexadoresComparison Between Properties and Indexers
Restringindo a acessibilidade ao acessadorRestricting Accessor Accessibility
Especificação da Linguagem C#C# Language Specification
Para obter mais informações, veja Indexadores na Especificação da linguagem C#.For more information, see Indexers in the C# Language Specification. A especificação da linguagem é a fonte definitiva para a sintaxe e o uso de C#.The language specification is the definitive source for C# syntax and usage.