如何lambda表达式内部工作? [英] How do lambda expressions work internally?

查看:207
本文介绍了如何lambda表达式内部工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然答案寻找到这个问题:的为什么是匿名方法中不允许out参数?我有一点点失落关于如何lambda表达式和匿名方法的实际工作。

While looking up the answer to this question: "Why is an out parameter not allowed within an anonymous method?" I've got a little lost about how do lambda expression and anonymous methods actually work.

在评论JaredPar指出,想象一下,例如,该OUT参数所指的堆栈中的局部变量。该拉姆达可以在未来任意点执行,从而可以执行时堆栈帧不再有效

In the comments JaredPar states that "Imagine for instance that the out parameter referred to a local variable on the stack. The lambda can execute at any arbitrary point in the future and hence could execute when that stack frame was no longer valid".

我指出,如果那不是与任何其他变量的情况下......这基本上让我怀疑什么,我真的了解lambda表达式。

I pointed out if wouldn't that be the case with any other variable... which basically make me wonder what to I really know about lambda expressions.

我心目中的东西是这样的:

The thing I have in mind is something like this:

public void Foo(ComplexObject val, out SomeDelegate outDelegate)
{
  ComplexObject obj = new ComplexObject(val)
  SomeDelegate = delegate(int other) { return (obj.value * other); }  
}

public void Bar()
{
  SomeDelegate MyDel = null;
  Foo(5, out MyDel);
  int finalRes = MyDel(100);
  // Whatever
}

在这种情况下我真的不知道发生了什么。 obj是堆栈这将不再是关于方法的返回有效所以annonymous方法应该可以(如果适用)来真正知道这是引用类型和复制,而不是参考价值的,如果它在一个参考...为什么不REF如果用例或多或少是相同的PARAMS工作?

In that situation I don't really know what's happening. obj is a reference on the stack which would no longer be valid on method return so the annonymous method should be able (if that works) to actually know that's a reference type and copy the reference instead of the value, if it does... why wouldn't ref params work if the "use case" is more or less the same?

推荐答案

我做了一个相当广泛的博客系列闭包的内部是如何工作的。这是写在VB.Net实施封锁,但底层细节非常类似于C#的。它应该提供你正在寻找

I did a fairly extensive blog series on how closures work internally. It's written for the VB.Net implementation of closures but the underlying details are very similar to C#'s. It should provide the answers you're looking for

下面是链接到所有其他条款

Here is the link to part 6 which links to all of the other articles

  • http://blogs.msdn.com/jaredpar/archive/2007/08/06/closures-in-vb-part-6-limitations.aspx

这篇关于如何lambda表达式内部工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆