找出为什么循环结束后,每个回调都会输出同一个值。 using System ;
using System . Collections . Generic ;
var callbacks = new List < Action >();
for ( int i = 0 ; i < 3 ; i ++ )
callbacks . Add (() => Console . WriteLine (i));
foreach ( Action callback in callbacks)
callback ();
查看答案
上一道练习 审查生成的报告通知器 审查AI代码
问问你的AI 让你的AI把这段代码改成引导式找错练习。
Claude ChatGPT 复制提示词 I am reading "找出为什么循环结束后,每个回调都会输出同一个值。" on CodeWiki (https://codewiki.com/zh/practice/spotbug/csharp/delegates-events/spotbug-for-loop-capture/).
Context (verbatim from the page):
"""
using System;
using System.Collections.Generic;
var callbacks = new List<Action>();
for (int i = 0; i < 3; i++)
callbacks.Add(() => Console.WriteLine(i));
foreach (Action callback in callbacks)
callback();
"""
Introduce three subtle bugs into the example above and let me find them. Reveal each answer only after I have guessed.
Answer in 中文. Keep code examples in csharp. Where you are unsure, say so.