并非所有代码路径都返回类型为&#39; System.Func <int>&#39; </int>的lambda表达式中的值

时间:2014-06-03 14:13:49

标签: c# lambda

我正在创建一个调用函数CountPixels的任务,如下所示

Task<int> task1 = new Task<int>(()=>{CountPixels(croppedBitmap, Color.FromArgb(255, 255, 255, 255));});

CountPixels的代码如下:

private int CountPixels(Bitmap croppedBitmap, Color target_color)
    {
        int height = croppedBitmap.Height;
        int width = croppedBitmap.Width;
        int matches = 0;
        List<int> x1range = new List<int>();
        List<int> y1range = new List<int>();
        for (int y1 = 0; y1 < height; y1++)
        {
            for (int x1 = 0; x1 < width; x1++)
            {
                if (croppedBitmap.GetPixel(x1, y1) == target_color
                {
                    matches++;
                    x1range.Add(x1);
                    y1range.Add(y1);
                }
            }
        }
        Console.WriteLine("before modification : {0} ms", sw.ElapsedMilliseconds);
        x1range.sort;
        y1range.sort;
        int x1max, y1max;
        x1max = x1range.Count - 1;
        y1max = y1range.Count - 1;
        try
        {
            fruit1.Text = "X1 MIN =  " + x1range[0] + "  X1 MAX =  " + x1range[x1max] + "  Y1 MIN =  " + y1range[0] + "  Y1 MAX =  " + y1range[y1max];
        }
        catch (Exception ex)
        {
            MessageBox.Show("" + ex);
        }
        return matches;
    }

我在task1行遇到错误:

  

并非所有代码路径都返回“System.Func int&gt;”类型的lambda表达式中的值

请帮帮我..我哪里错了? 谢谢!

3 个答案:

答案 0 :(得分:3)

这很容易。不要忘记返回值:

Task<int> task1 = new Task<int>(()=> { return CountPixels(croppedBitmap, Color.FromArgb(255, 255, 255, 255)); });

答案 1 :(得分:2)

尝试(我添加了return关键字)。

Task<int> task1 = new Task<int>(()=>{return CountPixels(croppedBitmap, Color.FromArgb(255, 255, 255, 255));})

虽然CountPixels返回一个int,但你没有在任务本身返回那个int。

答案 2 :(得分:2)

尝试删除lambda语句中的花括号:

Task<int> task1 = new Task<int>(()=> CountPixels(croppedBitmap, Color.FromArgb(255, 255, 255, 255)); );

different kinds个lamdas,例如这是表达式lambda (根据msdn):

(x, y) => x == y

返回表达式的结果。

这是语句lambda

(x, y) => { return x == y; }

因此,当您使用花括号创建语句lambda并且没有隐式返回时,您必须明确使用return来返回值。