Feedback

„for“ mal anders

Sprache: C#

Eine for-Schleife als int Extension. Die eigentliche Aktion wird als Block mit dem action<T> delegate übergeben.
public static void Times(this int count, Action<int> action)
{
    for (int i = 0; i < count; i++)
    {
        action(i);
    }
} 
public static void Times(this int count, Action<int> action)
{
    for (int i = 0; i < count; i++)
    {
        action(i);
    }
} 

5 Kommentare

  1. Willst du wirklich das dass Aufrufende int Objekt auch als Zählervariable genutzt wird seh ich das richtig? Oder willst du folgendes machen?
    [code]
    public static void Times(this int value,int count, Action action)
    {
    for (int i = 0; i < count; i++) { action(i); } } [/code] Sodass du [code] int i = 0; i.Times(10,Console.Writeline); [/code] So würde zwar 10 mal 0 ausgeben werden aber auch bei deiner Extension ist es ja ohne Side Effects.

  2. Sorry ich meinte das bei dem Ersten Code Beispiel natürlich so
    [code]
    public static void Times(this int value,int count, Action action)
    {
    for (int i = 0; i < count; i++) { action(value); } } [/code]

  3. Hmm das ist ganz ehrlich gesagt irgendwie mit der Kirche ums Dorf 😀 Dafür gibts wirklich bessere Methoden, ohne vorher über den Count zu gehen.