C#之委托

下面来调用这个方法,看一下委托的具体使用方法

   /// <summary>
    /// 实体模型
    /// </summary>
    public class Student
    {       
        public string Id { get; set; }       
        public string Name { get; set; }
    }

 

     
    /// 扩展方法   
    public static class DelegateExtend
    {
        
        /// 模仿Linq的Where操作        
        /// <typeparam name="T"></typeparam>
        /// <param name="scoure">数据源</param>
        /// <param name="func">委托(自定义bool条件)</param>      
        public static IEnumerable<T> ExtWhere<T>(this IEnumerable<T> scoure, Func<T, bool> func)
        {
            //遍历数据源的数据
            foreach (var item in scoure)
            {
                //请求委托完成条件的筛选返回bool
                bool bResult = func(item);
                //把通过筛选提交的数据源,返回出去
                if (bResult)
                {
                    yield return item;
                }
            }
        }
    }
     
    /// 扩展方法   
    public static class DelegateExtend
    {        
        /// 模仿Linq的Where操作        
        /// <typeparam name="T"></typeparam>
        /// <param name="scoure">数据源</param>
        /// <param name="func">委托(自定义bool条件)</param>
        /// <returns></returns>
        public static IEnumerable<T> ExtWhere<T>(this IEnumerable<T> scoure, Func<T, bool> func)
        {
            //遍历数据源的数据
            foreach (var item in scoure)
            {
                //请求委托完成条件的筛选返回bool
                bool bResult = func(item);//查看 id是不是等于1,如果等于1就直接yield直接返回
                //把通过筛选提交的数据源,返回出去
                if (bResult)
                {
                    yield return item;
                }
            }
        }
    }

 

 

            //查询出所有数据
            IEnumerable<Student> student = sql.QueryList<Student>();
第一种
//定义一个匿名方法,并赋值给委托 这个写法挺新奇
//传入一个类型,返回一个bool值,后面用deletegate() 直接就行 Func<Student, bool> func = delegate(Student s) { //自定义代码逻辑,返回bool类型 return s.Id.Equals("1"); };
//传入委托 IEnumerable<Student> list = student.ExtWhere(func);        //第二种方法,使用linq语法(自定义逻辑) IEnumerable<Student> list1 = student.ExtWhere(p => p.Id.Equals("1"));

 

posted @ 2021-10-14 17:02  ProZkb  阅读(35)  评论(0编辑  收藏  举报