当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - 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(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:

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... } );
分享给朋友:
您可能感兴趣的文章:
随机阅读: