代表和变量范围 [英] Delegates and variables scope

查看:43
本文介绍了代表和变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

public void SetMove(Position3D pos, float time, float linearity, bool relative)
{
    ExecuteOnActiveClients(delegate(NeuroClient client)
                               {
                                   client.Engine.GetProcAnimation(name).SetMove(pos, time, linearity, relative);
                               }, true, true);
}

ExecuteOnActiveClients将委托推送到队列中,并被异步使用,并具有以下签名:

Where ExecuteOnActiveClients pushes the delegate in a queue, consumed asynchronously, and has the following signature:

void ExecuteOnActiveClients(ClientDelegate action, Boolean parallel, Boolean wait, Boolean lockClient)

我有很多看起来像这样的功能,可以同时调用.

I have a lot of functions which look like this one, and which may be called concurrently.

我注意到我必须在执行ExecuteOnActiveClients之前将 name 的值(这是类的私有字段)的值存储在函数的变量中,以使此代码正常工作,因为如果我没有,委托使用的是 name 的最后一个值,而不是调用函数时字段具有的值.

I have noticed that I must store the value of name (which is a private field of the class) in a variable in the function before I execute ExecuteOnActiveClients to have this code work well, because if I don't, the delegate uses the last value of name, and not the value the field had when the function was called.

我想这是范围问题,因为该函数的参数(位置,时间,线性和相对)正确.

I guess this is a problem of scope, because the parameters of the function (pos, time, linearity and relative) are correct.

是否有一种方法可以强制委托在创建时使用 name 的值,而不是在执行时使用 name 的值?

Is there a way to force the delegate to use the value of name when it was created, and not the value of name when it is executed?

如果可能的话,我想避免将值存储在每个使用 ExecuteOnActiveClients 的函数中.

I'd like to avoid to store the value in each of the lot of functions which use ExecuteOnActiveClients if it possible.

预先感谢

迈克

推荐答案

当前,该委托根本不存储 name 的值.它捕获 this ,然后在引用它时使用它来解析 this.name .

Currently the delegate isn't storing the value of name at all. It's capturing this, and then using it to resolve this.name whenever you refer to it.

这是匿名方法和lambda表达式都起作用的方式,您无能为力,无法改变它们的行为:创建局部变量的解决方法.(那仍然会捕获该变量,而不是其当前值,但是可以确保以后不要更改该局部变量的值.)

This is the way both anonymous methods and lambda expressions work, and there's nothing you can do to change their behaviour: creating a local variable is the workaround. (That will still be capturing that variable rather than its current value, but you can presumably make sure you don't change the local variable's value afterwards.)

有关更多信息,以及容易陷入的另一个陷阱,我敦促您阅读Eric Lippert的博客文章关闭认为有害的循环变量"(

For more information, and another trap you can easily fall into, I urge you to read Eric Lippert's blog posts on "Closing over the loop variable considered harmful" (part 1, part 2).

这篇关于代表和变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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