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);
}
}
Alte URL:
/snippet/for-mal-anders/1367
Willst du wirklich das dass Aufrufende int Objekt auch als Zählervariable genutzt wird seh ich das richtig? Oder willst du folgendes machen? action)
[code]
public static void Times(this int value,int count, 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.
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]
Jo stimmt, ok dann ist alles klar.
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.
Richtig nur hat Columbus den Seeweg nicht neu erfunden 😉