C#中的Action<>和Func<>和Predicate

理解C#中的委托与泛型委托
本文详细解释了C#中的委托概念,包括如何使用`Action`和`Func`来创建无返回值和有返回值的委托,并通过实例展示了它们的应用。同时介绍了`Predicate`泛型委托的概念及使用方法。

其实他们都是委托【代理】的简写形式。

一、【action<>】指定那些只有输入参数,没有返回值的委托

namespace EventDemo
{
    class Program
    {
        public delegate void myDelegate(string str);  
        public static void HellowChinese(string strChinese)  
        {  
            Console.WriteLine("Good morning," + strChinese);  
            Console.ReadLine();  
        }  

        static void Main(string[] args)
        {
            //Delegate的代码
            myDelegate d = new myDelegate(HellowChinese);
            d("Mr wang");

            //用了Action之后呢
            Action<string> action = HellowChinese;
            action("Spring.");

            Console.ReadLine();
        }
    }
}

二、func<> 这个和上面的那个是一样的,区别是这个有返回值!

语法:
Func<参数,返回值>变量名=函数名 
Lambda表达式的调用方式
语法:(显示类型的参数列表)=>{语句}
eg:
Func<int,int,string>func=(x,y)=>(x*y).Tostring();
Console.WriteLine(fun(5,20));
namespace EventDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //类似委托功能
            Func<string, int> test = TsetMothod;
            Console.WriteLine(test("123"));
            Func<string, int> test1 = TsetMothod;


            //只需要调用这个类就可以减少重复的代码
            CallMethod<string>(test1, "123");
            //或者采用这种
            CallMethod<string>(new Func<string, int>(TsetMothod), "123");
            CallMethod(new Func<string, int>(TsetMothod), "123");

            Func<int, double, decimal, string> testFun = TestFun;
            double b = 2.3;
            decimal c = 666.7m;
            string strtestFun = testFun(1, b, c);
            Console.WriteLine("Func<int, double, decimal, string> testFun={0}", strtestFun);

            Console.ReadKey();
        }

        public static string TestFun(int a, double b, decimal c)
        {
            return "TestFun";
        }

        public static int TsetMothod(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return 1;
            }
            return 0;
        }

        public static void CallMethod<T>(Func<T, int> func, T item)
        {
            try
            {
                int i = func(item);
                Console.WriteLine(i);
            }
            catch (Exception e)
            {
            }
            finally
            {
            }
        }
    }
}

Predicate 泛型委托
  表示定义一组条件并确定指定对象是否符合这些条件的方法。此委托由 Array 和 List 类的几种方法使用,用于在集合中搜索元素。

public delegate bool Predicate<T>(T obj);
类型参数介绍:
   T: 要比较的对象的类型。
   obj: 要按照由此委托表示的方法中定义的条件进行比较的对象。
   返回值:如果 obj 符合由此委托表示的方法中定义的条件,则为 true;否则为 false。
看下面代码:
namespace EventDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> list = new List<string>() { "Mike", "Rose", "Steve" };
            var mike = list.Find(new Predicate<string>(HaveLengthFive));
            Console.WriteLine(mike);
            Console.ReadLine();
        }
        static bool HaveLengthFive(string value)
        {
            return value.Length == 5;
        }
    }
}
延伸:
  除了上面提到的外,你完全可以使用Predicate 定义新的方法,来加强自己代码。

public class GenericDelegateDemo
{
    List<String> listString = new List<String>()
    {
        "One","Two","Three","Four","Fice","Six","Seven","Eight","Nine","Ten"
    };

    public String GetStringList(Predicate<String> p)
    {
        foreach(string item in listString)
        {
            if (p(item))
                return item;
        }
        return null;
    }

    public bool ExistString()
    {
        string str = GetStringList((c) => { return c.Length <= 3 && c.Contains('S'); });
        if (str == null)
            return false;
        else
            return true;
    }
}



public interface IRepository<TEntity> where TEntity : BaseEntity { /// <summary> /// EF DBContext /// </summary> VOLContext DbContext { get; } ISqlDapper DapperContext { get; } /// <summary> /// 执行事务。将在执行的方法带入Action /// </summary> /// <param name="action"></param> /// <returns></returns> WebResponseContent DbContextBeginTransaction(Func<WebResponseContent> action); /// <summary> /// 通过条件查询数据 /// </summary> /// <param name="where"></param> /// <returns></returns> List<TEntity> Find(Expression<Func<TEntity, bool>> where); /// <summary> /// /// </summary> /// <param name="predicate"></param> /// <param name="orderBySelector">排序字段,数据格式如: /// orderBy = x => new Dictionary<object, bool>() { /// { x.BalconyName,QueryOrderBy.Asc}, /// { x.TranCorpCode1,QueryOrderBy.Desc} /// }; /// /// </param> /// <returns></returns> TEntity FindFirst(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, Dictionary<object, QueryOrderBy>>> orderBy = null); /// <summary> /// /// </summary> /// <param name="predicate">where条件</param> /// <param name="orderBy">排序字段,数据格式如: /// orderBy = x => new Dictionary<object, bool>() { /// { x.BalconyName,QueryOrderBy.Asc}, /// { x.TranCorpCode1,QueryOrderBy.Desc} /// }; /// </param> /// <returns></returns> IQueryable<TEntity> FindAsIQueryable(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, Dictionary<object, QueryOrderBy>>> orderBy = null); /// <summary> /// 通过条件查询数据 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="predicate">查询条件</param> /// <param name="selector">返回类型如:Find(x => x.UserName == loginInfo.userName, p => new { uname = p.UserName });</param> /// <returns></returns> List<T> Find<T>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, T>> selector); /// <summary> /// 根据条件,返回查询的类 /// </summary> /// <typeparam name="TFind"></typeparam> /// <param name="predicate"></param> /// <returns></returns> List<TFind> Find<TFind>(Expression<Func<TFind, bool>> predicate) where TFind : class; Task<TFind> FindAsyncFirst<TFind>(Expression<Func<TFind, bool>> predicate) where TFind : class; Task<TEntity> FindAsyncFirst(Expression<Func<TEntity, bool>> predicate); Task<List<TFind>> FindAsync<TFind>(Expression<Func<TFind, bool>> predicate) where TFind : class; Task<TEntity> FindFirstAsync(Expression<Func<TEntity, bool>> predicate); Task<List<TEntity>> FindAsync(Expression<Func<TEntity, bool>> predicate); Task<List<T>> FindAsync<T>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, T>> selector); Task<T> FindFirstAsync<T>(Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, T>> selector); /// <summary> /// 多条件查询 /// </summary> /// <typeparam name="Source"></typeparam> /// <param name="sources">要查询的多个条件的数据源</param> /// <param name="predicate">生成的查询条件</param> /// <returns></returns> List<TEntity> Find<Source>(IEnumerable<Source> sources, Func<Source, Expression<Func<TEntity, bool>>> predicate) where Source : class; /// <summary> /// 多条件查询 /// </summary> /// <typeparam name="Source"></typeparam> /// <param name="sources">要查询的多个条件的数据源</param> /// <param name="predicate">生成的查询条件</param> /// <param name="selector">自定义返回结果</param> /// <returns></returns> List<TResult> Find<Source, TResult>(IEnumerable<Source> sources, Func<Source, Expression<Func<TEntity, bool>>> predicate, Expression<Func<TEntity, TResult>> selector) where Source : class; /// <summary> /// 多条件查询 /// </summary> /// <typeparam name="Source"></typeparam> /// <param name="sources">要查询的多个条件的数据源</param> /// <param name="predicate">生成的查询条件</param> /// <returns></returns> IQueryable<TEntity> FindAsIQueryable<Source>(IEnumerable<Source> sources, Func<Source, Expression<Func<TEntity, bool>>> predicate) where Source : class; Task<bool> ExistsAsync(Expression<Func<TEntity, bool>> predicate); bool Exists(Expression<Func<TEntity, bool>> predicate); bool Exists<TExists>(Expression<Func<TExists, bool>> predicate) where TExists : class; Task<bool> ExistsAsync<TExists>(Expression<Func<TExists, bool>> predicate) where TExists : class; IIncludableQueryable<TEntity, TProperty> Include<TProperty>(Expression<Func<TEntity, TProperty>> incluedProperty); /// <summary> /// /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="pageIndex"></param> /// <param name="pagesize"></param> /// <param name="rowcount"></param> /// <param name="predicate"></param> /// <param name="orderBy"> /// 通过多个字段排序Expression<Func<TEntity, Dictionary<object, bool>>> /// orderBy = x => new Dictionary<object, bool>() { /// { x.BalconyName,QueryOrderBy.Asc}, /// { x.TranCorpCode1,QueryOrderBy.Desc} /// }; /// <param name="selectorResult">查询返回的对象</param> /// <returns></returns> List<TResult> QueryByPage<TResult>(int pageIndex, int pagesize, out int rowcount, Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, Dictionary<object, QueryOrderBy>>> orderBySelector, Expression<Func<TEntity, TResult>> selectorResult, bool returnRowCount = true); List<TResult> QueryByPage<TResult>(int pageIndex, int pagesize, Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, Dictionary<object, QueryOrderBy>>> orderBy, Expression<Func<TEntity, TResult>> selectorResult = null); /// <summary> /// /// </summary> /// <param name="pageIndex"></param> /// <param name="pagesize"></param> /// <param name="rowcount"></param> /// <param name="predicate"></param> /// <param name="orderBy"></param> /// /// 通过多个字段排序Expression<Func<TEntity, Dictionary<object, bool>>> /// orderBy = x => new Dictionary<object, bool>() { /// { x.BalconyName,QueryOrderBy.Asc}, /// { x.TranCorpCode1,QueryOrderBy.Desc} /// }; /// <returns></returns> List<TEntity> QueryByPage(int pageIndex, int pagesize, out int rowcount, Expression<Func<TEntity, bool>> predicate, Expression<Func<TEntity, Dictionary<object, QueryOrderBy>>> orderBy, bool returnRowCount = true); IQueryable<TFind> IQueryablePage<TFind>(int pageIndex, int pagesize, out int rowcount, Expression<Func<TFind, bool>> predicate, Expression<Func<TEntity, Dictionary<object, QueryOrderBy>>> orderBy, bool returnRowCount = true) where TFind : class; IQueryable<TEntity> IQueryablePage(IQueryable<TEntity> queryable, int pageIndex, int pagesize, out int rowcount, Dictionary<string, QueryOrderBy> orderBy, bool returnRowCount = true); /// <summary> /// /// </summary> /// <param name="entity"></param> /// <param name="properties">指定更新字段:x=>new {x.Name,x.Enable}</param> /// <param name="saveChanges">是否保存</param> /// <returns></returns> int Update(TEntity entity, Expression<Func<TEntity, object>> properties, bool saveChanges = false); /// <summary> /// /// </summary> /// <param name="entity"></param> /// <param name="properties">指定更新字段:x=>new {x.Name,x.Enable}</param> /// <param name="saveChanges">是否保存</param> /// <returns></returns> int Update<TSource>(TSource entity, Expression<Func<TSource, object>> properties, bool saveChanges = false) where TSource : class; int Update<TSource>(TSource entity, bool saveChanges = false) where TSource : class; int Update<TSource>(TSource entity, string[] properties, bool saveChanges = false) where TSource : class; int UpdateRange<TSource>(IEnumerable<TSource> entities, bool saveChanges = false) where TSource : class; /// <summary> /// /// </summary> /// <param name="entity"></param> /// <param name="properties">指定更新字段:x=>new {x.Name,x.Enable}</param> /// <param name="saveChanges">是否保存</param> /// <returns></returns> int UpdateRange<TSource>(IEnumerable<TSource> models, Expression<Func<TSource, object>> properties, bool saveChanges = false) where TSource : class; int UpdateRange<TSource>(IEnumerable<TSource> entities, string[] properties, bool saveChanges = false) where TSource : class; /// <summary> ///修改时同时对明细的添加、删除、修改 /// </summary> /// <param name="entity"></param> /// <param name="updateDetail">是否修改明细</param> /// <param name="delNotExist">是否删除明细不存在的数据</param> /// <param name="updateMainFields">主表指定修改字段</param> /// <param name="updateDetailFields">明细指定修改字段</param> /// <param name="saveChange">是否保存</param> /// <returns></returns> WebResponseContent UpdateRange<Detail>(TEntity entity, bool updateDetail = false, bool delNotExist = false, Expression<Func<TEntity, object>> updateMainFields = null, Expression<Func<Detail, object>> updateDetailFields = null, bool saveChange = false) where Detail : class; void Delete(TEntity model, bool saveChanges=false); /// <summary> /// /// </summary> /// <param name="keys"></param> /// <param name="delList">是否将子表的数据也删除</param> /// <returns></returns> int DeleteWithKeys(object[] keys, bool delList = false); void Add(TEntity entities, bool SaveChanges = false); void AddRange(IEnumerable<TEntity> entities, bool SaveChanges = false); Task AddAsync(TEntity entities); Task AddRangeAsync(IEnumerable<TEntity> entities); void AddRange<T>(IEnumerable<T> entities, bool saveChanges = false) where T : class; void BulkInsert(IEnumerable<TEntity> entities, bool setOutputIdentity = false); int SaveChanges(); Task<int> SaveChangesAsync(); int ExecuteSqlCommand(string sql, params SqlParameter[] sqlParameters); List<TEntity> FromSql(string sql, params SqlParameter[] sqlParameters); /// <summary> /// 执行sql /// 使用方式 FormattableString sql=$"select * from xx where name ={xx} and pwd={xx1} ", /// FromSqlInterpolated内部处理sql注入的问题,直接在{xx}写对应的值即可 /// 注意:sql必须 select * 返回所有TEntity字段, /// </summary> /// <param name="formattableString"></param> /// <returns></returns> IQueryable<TEntity> FromSqlInterpolated([System.Diagnostics.CodeAnalysis.NotNull] FormattableString sql); /// <summary> /// 取消上下文跟踪 /// 更新报错时,请调用此方法:The instance of entity type 'XXX' cannot be tracked because another instance with the same key value for {'XX'} is already being tracked. /// </summary> /// <param name="entity"></param> void Detached(TEntity entity); void DetachedRange(IEnumerable<TEntity> entities); }
最新发布
08-01
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值