Not all code paths return a value in lambda expres

2019-03-04 16:12发布

问题:

This question already has an answer here:

  • Lambda expression returning error 4 answers

I'm creating a task of calling a function CountPixels as shown below

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

The code for CountPixels is as follows:

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;
    }

I'm getting an Error at the task1 line:

Not all code paths return a value in lambda expression of type 'System.Func int>'

Please help me out..where am I going wrong? Thank you!

回答1:

It's easy. Don't forget to return the value:

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


回答2:

Try (I've added the return keyword).

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

Although CountPixels returns an int you're not returning that int in the task itself.



回答3:

try removing the curly braces in your lambda statement:

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

There are different kinds of lamdas, for example this is an expression lambda (according to msdn):

(x, y) => x == y

It returns the result of the expression.

And this is the statement lambda:

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

So, when you use curly braces you are creating a statement lambda and there is no implicit returning, you have to explicitly use the return to return a value.



标签: c# lambda