[英]C# Func delegate
I am adding range of integers (101,105) using Func<> delegate.I suppose to get 101,102,..105 as output while executing the following.But I am getting 204,204,..... What went wrong? 我正在使用Func <> delegate添加整数范围(101,105)。我想在执行以下操作时得到101,102,.. 105作为输出。但是我得到了204,204,.....出了什么问题?
class MainClass
{
static List<Func<int>> somevalues = new List<Func<int>>();
static void Main()
{
foreach (int r in Enumerable.Range(100, 105))
{
somevalues.Add(() => r);
}
ProcessList(somevalues);
Console.ReadKey(true);
}
static void ProcessList(List<Func<int>> someValues)
{
foreach (Func<int> function in someValues)
{
Console.WriteLine(function());
}
}
}
See 看到
http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!689.entry http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!689.entry
or 要么
http://blogs.msdn.com/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx http://blogs.msdn.com/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx
foreach (int r in Enumerable.Range(100, 105))
{
int s = r;
somevalues.Add(() => s);
}
I think, you will need to capture the outer variable into a temp value to achieve the output, you need. 我想,你需要将外部变量捕获到一个临时值来实现输出。 I am not sure of what is the concept called (captured variables maybe).
我不确定所谓的概念是什么(捕获变量可能)。
THe Range method signiture is like follows: 范围方法签名如下:
Range(int start, int count);
you are saying "start at 100 and give me the next 105 numbers". 你说的是“从100开始给我下一个105号码”。
not, "start at 100 and finish at 105". 不,“从100开始到105完成”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.