Func<T, bool>与Expression<Func<T, bool>>的区别

Func<T, bool>与Expression<Func<T, bool>>的区别


Func<T, bool>是委托(delegate)

Expression<Func<T, bool>>是表达式

Expression编译后就会变成delegate,才能运行。比如

Expression<Func<int, bool>> ex = x=>x < 100;

 

// 将表达式树描述的 lambda 表达式编译为可执行代码,并生成表示该 lambda 表达式的委托。

Func<int, bool> func = ex.Compile();

 

 

然后你就可以调用func:

func(5) //-返回 true

func(200) //- 返回 false

而表达式是不能直接调用的。

案例:

public class DB
{
static public ISession Session
{

get { return SessionManager.GetCurrentSession(); }
}

//错误的代码
static public IList<T> Query1<T>(Func<T, bool> where)
{
return Session.Query<T>().Where(where).ToList();
}

//正确的代码
static public IList<T> Query2<T>(Expression<Func<T, bool>> where)
{
return Session.Query<T>().Where(where).ToList();
}
}

//不正确的查询代码如直接<Func<T, bool>作为参数造成的数据库全表查询

IList<Person> DB.Query1<Person>(obj=>obj.age>12); //查询年龄大约12

 

//正确的做法是使用Expression作为参数

IList<Person> DB.Query2<Person>(obj=>obj.age>12); //查询年龄大约12

 

使用这两种参数的函数对调用者来说发现问题,不过还是可以通过输出的SQL语句看出问题,使用Func直接作为参数,SQL中没有where语句,直接进行了全库检索。


注:
Delegate至少0个参数,至多32个参数,可以无返回值,也可以指定返回值类型。这个是祖宗。
Func可以接受0个至16个传入参数,必须具有返回值。
Action可以接受0个至16个传入参数,无返回值。
Predicate只能接受一个传入参数,返回值为bool类型。

转载于:https://www.cnblogs.com/SafeSimple/p/7818759.html

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值