无法将表达式类型“lambda表达式”转换为返回类型“System.Linq.Expressions.Expression<System.Func<IProduct,string,bool>>”

3

好的,我明白了。为什么第一个函数是错误的(lambda表达式中有波浪线),而第二个函数是正确的(也就是它可以编译通过)?

    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");

    }
4个回答

7

你的第一个函数将需要两个参数。 Func<x,y,z> 定义了两个参数和返回值。因为你的参数中既有 IProduct 也有 string,所以你的 lambda 表达式需要两个参数。

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

你的第二个函数只有一个参数Func<x,y>,这意味着函数签名只有一个参数,因此你的lambda语句可以编译。


3

中间的string是用来做什么的?你可以通过以下方式使其编译:

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

或许您的意思是:
public static Expression<Func<IProduct, string, bool>> IsValidExpression()
{
    return (h,val) => h.product_name == val;
}

?


我的猜测是OP不知道val被提升了,因此不是lambda表达式生成的方法签名的一部分。 - Rune FS

0

Func<IProduct, string, bool> 是一个委托,其方法签名如下:

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

所以

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

返回类型和返回值之间存在差异。您正试图返回类型为Expression<Func<IProduct, bool>>的对象。

val参数不是您委托给的方法的参数,但将被提升(成为实现结果函数的类的一部分),并且由于它不是结果方法的参数,因此不应该成为Func类型声明的一部分。


既然这是一个Expression(而不是委托),它并不像你描述的那样 - 没有“结果函数”;它是一个表达式树... - Marc Gravell
@marc 你说得对,Expression<> 是一个表达式树而不是一个方法。我为“Expression 树可以编译成的方法”这个术语苦苦思索,试图将其表述为“结果函数”,但是 Func<> 是委托类型的说法是正确的 :) - Rune FS

-1
在尝试修复Lambda表达式之前,请确保已将以下引用添加到相关的cs文件中:
using System.Linq;
using System.Linq.Expressions;

缺少这些引用可能会导致相同的错误("无法将 Lambda 表达式转换为类型 'System.Linq.Expressions.Lambda Expression',因为它不是委托类型")。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接