小编Mou*_*hyi的帖子

c#在Lambda表达式中声明变量

下面的代码输出33而不是012.我不明白为什么在每次迭代中没有捕获新变量loopScopedi而不是捕获相同的变量.

Action[] actions = new Action[3];

for (int i = 0; i < 3; i++)
{

   actions [i] = () => {int loopScopedi = i; Console.Write (loopScopedi);};
}

foreach (Action a in actions) a();     // 333
Run Code Online (Sandbox Code Playgroud)

Hopwever,这段代码产生012.两者之间有什么区别?

Action[] actions = new Action[3];

for (int i = 0; i < 3; i++)
{
    int loopScopedi = i;
    actions [i] = () => Console.Write (loopScopedi);
}

foreach (Action a in actions) a();     // 012
Run Code Online (Sandbox Code Playgroud)

c# lambda

11
推荐指数
1
解决办法
1380
查看次数

保存并重复使用块进行方法调用

我使用相同的块多次调用 RestClient :: Resource#get(additional_headers = {},&block)方法,但在不同的资源上,我想知道是否有办法将块保存到变量中,或者保存它每次都将Proc转换为块.

编辑:

我做了以下事情:

resource = RestClient::Resource.new('https://foo.com')
redirect  =  lambda do  |response, request, result, &block|
  if [301, 302, 307].include? response.code
     response.follow_redirection(request, result, &block)
   else
      response.return!(request, result, &block)
   end
end
@resp = resource.get (&redirect)
Run Code Online (Sandbox Code Playgroud)

我明白了: Syntax error, unexpected tAMPER

ruby

10
推荐指数
1
解决办法
4980
查看次数

标签 统计

c# ×1

lambda ×1

ruby ×1