简体   繁体   中英

Cannot convert expression type 'lambda expression' to return type 'System.Linq.Expressions.Expression<System.Func<IProduct,string,bool>>'

Ok, I'm lost. Why is the 1st function WRONG (squiglies in the lambda expression), but the 2nd one is RIGHT (meaning it compiles)?

    public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
    {
        return (h => h.product_name == val);

    }

    public static Expression<Func<IProduct, bool>> IsValidExpression2()
    {
        return (m => m.product_name == "ACE");

    }

Your first function is going to need two arguments. Func<x,y,z> defines two parameters and the return value. Since you have both an IProduct and a string as parameters, you'll need two arguments in your lambda.

  public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
  {
        return ((h, i) => h.product_name == val);
  }

Your second function is only Func<x,y> , so that means that the function signature has but one parameter, and thus your lambda statement compiles.

What is the middle string intended to do? You can make it compile by:

public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
{
    return (h,something) => h.product_name == val;
}

Or maybe you mean:

public static Expression<Func<IProduct, string, bool>> IsValidExpression()
{
    return (h,val) => h.product_name == val;
}

?

Func<IProduct, string, bool> is a delegate to a method with the following signature:

bool methodName(IProduct product, string arg2)
{
  //method body
  return true || false;
}

so

public static Expression<Func<IProduct, string, bool>> IsValidExpression(string val)
{
    return (h => h.product_name == val);
}

has a differance between the return type and the returned value. you are trying to return an object of the type Expression<Func<IProduct, bool>> .

the val argument is not an argument to the method you're delegating to but will be hoisted (made part of a class implementing the resulting function) and since it's not an argument to the resulting method it should not be part of the Func type delclaration

Before trying to fix the lambda expression be sure that the following references were added to the related cs file:

using System.Linq;
using System.Linq.Expressions;

The lack of these references may cause the same error as well ( "Cannot convert lambda expression to type 'System.Linq.Expressions.Lambda Expression' because it is not a delegate type" ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM