秦之声

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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类型。

posted on 2017-11-11 12:41  秦之声  阅读(718)  评论(0编辑  收藏  举报