¿Cómo puedo sobrecargar el operador de corchete cuadrado en C#?


DataGridView, por ejemplo, le permite hacer esto:

DataGridView dgv = ...;
DataGridViewCell cell = dgv[1,5];

Pero para la vida de mí no puedo encontrar la documentación en el operador índice/corchete. ¿Cómo lo llaman? ¿Dónde se implementa? Puede tirar? ¿Cómo puedo hacer lo mismo en mis propias clases?

ETA: Gracias por todas las respuestas rápidas. Brevemente: la documentación relevante está bajo la propiedad "Item" ; la forma de sobrecargar es declarando una propiedad como public object this[int x, int y]{ get{...}; set{...} }; el indexador para DataGridView no lanza, al menos según la documentación. No menciona lo que sucede si proporciona coordenadas no válidas.

ETA De nuevo: OK, a pesar de que la documentación no hace mención de ello(naughty Microsoft!), resulta que el indexador para DataGridView de hecho lanzará una ArgumentOutOfRangeException si lo suministra con coordenadas no válidas. Una advertencia justa.

Author: Coderer, 2008-11-13

8 answers

Puedes encontrar cómo hacerlo aquí. En resumen es:

public object this[int i]
{
    get { return InnerList[i]; }
    set { InnerList[i] = value; }
}
 331
Author: Ruben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-03-22 14:32:38

Esa sería la propiedad del artículo: http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx

Tal vez algo como esto funcionaría:

public T Item[int index, int y]
{ 
    //Then do whatever you need to return/set here.
    get; set; 
}
 41
Author: Ricardo Villamil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-13 19:26:09
Operators                           Overloadability

+, -, *, /, %, &, |, <<, >>         All C# binary operators can be overloaded.

+, -, !,  ~, ++, --, true, false    All C# unary operators can be overloaded.

==, !=, <, >, <= , >=               All relational operators can be overloaded, 
                                    but only as pairs.

&&, ||                  They can't be overloaded

() (Conversion operator)        They can't be overloaded

+=, -=, *=, /=, %=                  These compound assignment operators can be 
                                    overloaded. But in C#, these operators are
                                    automatically overloaded when the respective
                                    binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof  These operators can't be overloaded

    [ ]                             Can be overloaded but not always!

Fuente de la información

Para el soporte:

public Object this[int index]
{

}

PERO

El operador de indexación de matriz no se puede sobrecargar; sin embargo, los tipos pueden definir indexadores, propiedades que toman uno o más parámetros. Los parámetros del indexador están encerrados entre corchetes, al igual que los índices de matriz, pero los parámetros del indexador se pueden declarar de cualquier tipo (a diferencia de los índices de matriz, que deben ser integrales).

De MSDN

 23
Author: Patrick Desjardins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-13 17:40:17
public class CustomCollection : List<Object>
{
    public Object this[int index]
    {
        // ...
    }
}
 6
Author: Jason Miesionczek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-13 19:25:08

Para CLI C++ (compilado con /clr) ver este enlace MSDN.

En resumen, a una propiedad se le puede dar el nombre "default":

ref class Class
{
 public:
  property System::String^ default[int i]
  {
    System::String^ get(int i) { return "hello world"; }
  }
};
 4
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-21 20:36:57

Si está utilizando C # 6 o posterior, puede usar la sintaxis con cuerpo de expresión para el indexador de solo get:

public object this[int i] => this.InnerList[i];

 4
Author: amoss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-18 21:44:23

Aquí hay un ejemplo que devuelve un valor de un objeto de lista interna. Debería darte la idea.

  public object this[int index]
  {
     get { return ( List[index] ); }
     set { List[index] = value; }
  }
 2
Author: Rob Prouse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-11-13 19:27:48

Si se refiere al indexador de matriz,, Se sobrecarga que simplemente escribiendo una propiedad de indexador.. Y se puede sobrecargar, (escribir tantos como quieras) indexer propiedades siempre y cuando cada uno tiene una firma de parámetro diferente

public class EmployeeCollection: List<Employee>
{
    public Employee this[int employeeId]
    {   
        get 
        { 
            foreach(var emp in this)
            {
                if (emp.EmployeeId == employeeId)
                    return emp;
            }

            return null;
        }
    }

    public Employee this[string employeeName]
    {   
        get 
        { 
            foreach(var emp in this)
            {
                if (emp.Name == employeeName)
                    return emp;
            }

            return null;
        }
    }
}
 1
Author: Charles Bretana,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-03 20:10:42