有没有办法向 Lambda 添加扩展方法?
在此示例中,我想将 .loop({quantity},{sleepvalue})
添加到一个方法,
我让它与此一起使用:
this.loop(count, 500,
()=>{
var image = Screenshots.getScreenshotOfDesktop();
pictureBox.load(image);
images.Add(image);
updateTrackBar();
});
使用此扩展方法:
public static void loop(this Object _object, int count, int delay, MethodInvoker methodInvoker)
{
for(int i=0; i < count; i++)
{
methodInvoker();
_object.sleep(delay);
}
}
这意味着调用语法是:
this.loop(15,500, () => {...code...});
但理想情况下我想做的是这样的:
()=> { ...code...}.loop(10,500);
除非我这样做,否则它不起作用:
new MethodInvoker(()=>{...code...}).loop(10,500);
它将与此版本的扩展方法一起使用:
public static void loop(this MethodInvoker methodInvoker, int count, int delay)
{
for(int i=0; i < count; i++)
{
methodInvoker();
Processes.Sleep(delay);
}
}
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,不幸的是没有。
我很久以前就在博客中讨论过这个问题 :(
但是,通过正确选择缩进,您可以使其看起来几乎与普通循环相同:
这就是我的许多并行扩展示例的样子
不会将其作为您实际上不会使用的东西的扩展方法,只是为了您可以使用“this”而不是真实的类型名称......除非您有一个真正的类型名称,否则不会无论如何,用于称为“on”的对象
(我还建议遵循 .NET 命名约定 - 让您的方法采用 PascalCase。)
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.)
我真的建议不要尝试这样做。
在我看来,在核心类型(例如委托/lambda 类型或 System.Object)上实现扩展方法通常是一个坏主意。
这只会造成混乱。我认为您提出的语法没有什么优势:
对我来说,这远不如以下可读性:
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:
To me, that is far less readable than: