匿名方法中包含的变量出错

问题描述 投票:0回答:1

我有以下方法。当调用Writeline方法时,出现缺失的结果。第二条Writeline的结果必须是true,否则就是false,请问你能告诉我吗?

    public static void IsGreater()
    {
       var biggerThanNumber = new Predicate<int>[10];
       for (int index = 0; index < biggerThanNumber.Length; ++index)
       {
         biggerThanNumber[index] = value => value > index; 
       }
       Console.WriteLine(biggerThanNumber[5](20)); //True
       Console.WriteLine(biggerThanNumber[5](6));  //False
    }
c# anonymous-methods
1个回答
1
投票

将方法改为将循环变量复制到本地引用中,以避免循环中lambda闭合的问题。在你的方法中,index的值总是10,因此第二个控制台返回false。更多信息请查看 职位

    public static void IsGreater()
    {
        var biggerThanNumber = new Predicate<int>[10];
        for (int index = 0; index < biggerThanNumber.Length; ++index)
        {
            int localCopy = index;
            biggerThanNumber[index] = value => value > localCopy;
        }
        Console.WriteLine(biggerThanNumber[5](20)); //True
        Console.WriteLine(biggerThanNumber[5](6));  //True
    }
© www.soinside.com 2019 - 2024. All rights reserved.