2012-06-12 7 views
6

Estoy intentando convertir el time de Ruby en C#, pero ahora estoy atascado.Convierta los tiempos de Ruby en C#

Aquí está mi intento:

public static class Extensions 
{ 
    public static void Times(this Int32 times, WhatGoesHere?) 
    { 
     for (int i = 0; i < times; i++) 
      ??? 
    } 
} 

Soy nuevo en C#, y tal vez esto se debe ser fácil, y sé que quiero usar Extensionmethods. Pero dado que las funciones no son de "primera clase" en C#, estoy estancado por ahora.

Entonces, ¿qué parametertype debería usar para WhatGoesHere?

Respuesta

5

Usted puede utilizar el tipo de Action:

public static class Extensions 
{ 
    public static void Times(this Int32 times, Action<Int32> action) 
    { 
     for (int i = 0; i < times; i++) 
      action(i); 
    } 
} 

class Program 
{ 
    delegate void Del(); 

    static void Main(string[] args) 
    { 
     5.Times(Console.WriteLine); 
     // or 
     5.Times(i => Console.WriteLine(i)); 
    } 
} 

también echar un vistazo here para aprender acerca de los delegados.

+0

Gracias! No sabía sobre delegados. –

+0

No hay problema ..... – sloth

Cuestiones relacionadas