Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created April 22, 2014 22:08
Show Gist options
  • Save Fhernd/11196104 to your computer and use it in GitHub Desktop.
Save Fhernd/11196104 to your computer and use it in GitHub Desktop.
Demostración de indexers personalizados en C#.
using System;
using System.Collections.Generic;
using System.Linq;
namespace Recetas.Ch01
{
public class ReporteTiempo
{
public int DiaSemana
{
get;
set;
}
public int TemperaturaDiaria
{
get;
set;
}
public int TemperaturaPromedio
{
get;
set;
}
}
public class PronosticoTiempo
{
private int[] temperaturas = { 13, 19, 23, 7, 23, 17, 7 };
IList<string> diasSemana = new List<string>() {"Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo" };
public ReporteTiempo this[string dia]
{
get
{
// Índice del día de la semana
int indiceDia = diasSemana.IndexOf(dia);
return new ReporteTiempo() { DiaSemana = indiceDia, TemperaturaDiaria = temperaturas[indiceDia], TemperaturaPromedio = CalcularTemperatura(indiceDia) };
}
set
{
temperaturas[diasSemana.IndexOf(dia)] = value.TemperaturaDiaria;
}
}
private int CalcularTemperatura(int diaSemana)
{
int[] tmp = new int[diaSemana + 1];
Array.Copy( temperaturas, 0, tmp, 0, diaSemana + 1);
return (int) tmp.Average();
}
}
public class Prueba
{
public static void Main()
{
// Creación pronóstico tiempo
PronosticoTiempo pronostico = new PronosticoTiempo();
// Uso del indixer para el pronóstico
string[] dias = {"Lunes", "Martes", "Jueves", "Sábado"};
foreach (string dia in dias)
{
ReporteTiempo reporte = pronostico[dia];
Console.WriteLine ("Día: {0}, Índice día: {1}, Temperatura: {2}, Promedio: {3}", dia, reporte.DiaSemana, reporte.TemperaturaDiaria, reporte.TemperaturaPromedio);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment