In this example I want to add a .loop({quantity},{sleepvalue}) to a method
I got it to work with this:
this.loop(count, 500,
()=>{
var image = Screenshots.getScreenshotOfDesktop();
pictureBox.load(image);
images.Add(image);
updateTrackBar();
});
using this extension method:
public static void loop(this Object _object, int count, int delay, MethodInvoker methodInvoker)
{
for(int i=0; i < count; i++)
{
methodInvoker();
_object.sleep(delay);
}
}
which means that the invocation syntax is:
this.loop(15,500, () => {...code...});
but ideally what I wanted to do was something like:
()=> { ...code...}.loop(10,500);
which doesn’t work unless I do it like this:
new MethodInvoker(()=>{...code...}).loop(10,500);
which will work with this version of the extension method:
public static void loop(this MethodInvoker methodInvoker, int count, int delay)
{
for(int i=0; i < count; i++)
{
methodInvoker();
Processes.Sleep(delay);
}
}
No, unfortunately there isn’t.
I blogged about this quite a while ago 🙁
However, with the right choice of indentation, you can make it look almost identical to a normal loop:
That’s what a lot of the Parallel Extensions samples look like
I wouldn’t make it an extension method on something you’re not actually going to use, just so that you can use “this” instead of the real type name… not unless you’ve got a real use for the object it’s called “on”, anyway.
(I’d also suggest following .NET naming conventions – make your methods PascalCase.)