开发者

Is there a way to add an Extension Method to a Lambda?

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(thi开发者_StackOverflows 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:

HelperType.Loop(count, 500, () =>
{
   // Code here
});

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.)


I really advise not to try to do this.

It's often a bad idea, in my opinion, to implement extension methods on core types, such as a delegate/lambda type, or System.Object.

This just causes confusion. I see little advantage to your proposed syntax:

() => { ..code... }.Loop(10, 500);

To me, that is far less readable than:

Utilities.RepeatWithDelay(10, 500, () => {....code... } );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜