下面的代码输出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) 我使用相同的块多次调用 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