對於我之前項目中的統一條件過濾采用了dictinary來實現的,優點就是方法簽名統一了,缺點不用說,就是字典的鍵容易寫錯,感覺一進入.net3.5之后,一切都要和Expression聯系在一起,我們在創建一個Expression(表達式樹)時,可以使用lambda表達式去創建,很容易:
1 Expression<Func<string, bool>> predicate= name=>name=="zzl";
可以看到,它其它由一個委托組成,輸入參數是個字符,輸出是個布爾值,在LINQ中這種技術被廣泛的使用在擴展方法中,如Where擴展方法:
1 public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate) 2 { 3 if (source == null) 4 { 5 throw System.Linq.Error.ArgumentNull("source"); 6 } 7 if (predicate == null) 8 { 9 throw System.Linq.Error.ArgumentNull("predicate"); 10 } 11 return source.Provider.CreateQuery<TSource>(Expression.Call(null, ((MethodInfo) MethodBase.GetCurrentMethod()).MakeGenericMethod(new Type[] { typeof(TSource) }), new Expression[] { source.Expression, Expression.Quote(predicate) })); 12 }
無可厚非,表達式樹的出現,lambda表達式的支持,是.net開發人員的福音,也是.net3.5中更大的亮點了。
說正文了,以前我的寫統一的參數簽名時,使用的是dictionary,代碼中可以是這樣的
1 Common.VPredication vp = new Common.VPredication(); 2 Common.PagingParam pp = new Common.PagingParam(page ?? 1, VConfig.WebConstConfig.PageSize); 3 4 vp.AddItem("userId", userID); 5 if (_gid != 0) 6 vp.AddItem("gid", _gid);
統一的方法簽名:
1 Common.Page.PagedList<Entity.Res_Item> GetList(Common.VPredication vp, Common.PagingParam pp)
而有了表達式樹的集合后,完成可以把過濾條件寫在它里面,這樣構建條件變成了這樣:
1 PredicateList<UserBases> zzl = new PredicateList<UserBases>(); 2 zzl.Add(i => i.Name.Contains("zzl")); 3 zzl.Add(i => i.UserID == 1); 4 GetModel(zzl).ForEach(i => Console.WriteLine(i.UserID + i.Name));
而方法簽名仍然是很統一,只是變成了表達式樹的樣子,有點強類型的味道,呵呵:
1 List<UserBases> GetModel(PredicateList<UserBases> param)
而PredicateList類型的原代碼,我也公開一下吧,呵呵,大家一共分享:
1 /// <summary> 2 /// 功能:條件過濾類 3 /// 作者:張占嶺 4 /// 日期:2012-6-7 5 /// </summary> 6 public class PredicateList<TEntity> : IEnumerable<Expression<Func<TEntity, bool>>> where TEntity : class 7 { 8 List<Expression<Func<TEntity, bool>>> expressionList; 9 public PredicateList() 10 { 11 expressionList = new List<Expression<Func<TEntity, bool>>>(); 12 } 13 /// <summary> 14 /// 添加到集合 15 /// </summary> 16 /// <param name="predicate"></param> 17 public void Add(Expression<Func<TEntity, bool>> predicate) 18 { 19 expressionList.Add(predicate); 20 } 21 /// <summary> 22 /// 從集合中移除 23 /// </summary> 24 /// <param name="predicate"></param> 25 public void Remove(Expression<Func<TEntity, bool>> predicate) 26 { 27 expressionList.Remove(predicate); 28 } 29 #region IEnumerable 成員 30 31 public IEnumerator GetEnumerator() 32 { 33 return expressionList.GetEnumerator(); 34 } 35 36 #endregion 37 38 #region IEnumerable<Expression<Func<TEntity>>> 成員 39 40 IEnumerator<Expression<Func<TEntity, bool>>> IEnumerable<Expression<Func<TEntity, bool>>>.GetEnumerator() 41 { 42 return expressionList.GetEnumerator(); 43 } 44 45 #endregion 46 }