Scope of anonymous methods

前端 未结 4 973
小蘑菇
小蘑菇 2020-12-30 08:45

One nice thing about anonymous methods is that I can use variables that are local in the calling context. Is there any reason why this does not work for out-parameters and f

4条回答
  •  既然无缘
    2020-12-30 09:43

    The problem is that your Str1 variable is not "owned" by ReturnTwoStrings, so that your anonymous method cannot capture it.

    The reason it cannot capture it, is that the compiler does not know the ultimate owner (somewhere in the call stack towards calling ReturnTwoStrings) so it cannot determine where to capture it from.

    Edit: (Added after a comment of Smasher)

    The core of anonymous methods is that they capture the variables (not their values).

    Allen Bauer (CodeGear) explains a bit more about variable capturing in his blog.

    There is a C# question about circumventing your problem as well.

提交回复
热议问题