委托 Action<>,Func<>,Predicat<>

Action是无返回值的泛型委托,参数0~16个

Func是有返回值的泛型委托,参数0~16个

Predicate<>是返回bool类型的委托,参数为有且仅有一个

如果说lambda是为了简化委托的后半部分方法体的初始化,那么Func他们就是为了简化委托的定义部分(前半部分)。

Predicat<>

复制代码
 1 public delegate int DelegateProcess(int num1, int num2);
 2 
 3         public void Init()
 4         {
 5             //第一种写法
 6             DelegateProcess process = new DelegateProcess(Multiply);
 7 
 8             //第二种写法
 9             DelegateProcess process1 = Multiply;
10 
11             //第三种写法  匿名委托
12             DelegateProcess process2 = delegate (int a, int b)
13             {
14                 return a * b;
15             };
16 
17             //第四种写法 Lamdba表达式
18             DelegateProcess process3 = (int a, int b) => { return a * b; };
19 
20             var result1 = process(1, 2);
21 
22             var result2 = Get(process);
23         }
24         public int Multiply(int a, int b)
25         {
26             return a * b;
27         }
28 
29         public int Get(DelegateProcess process)
30         {
31             //参数逻辑处理
32             var arg1 = 4 * 5;
33             var arg2 = 3;
34            return process(arg1, arg2);
35         }
复制代码

 

Func<>

复制代码
 1         /// <summary>
 2         /// Func<T>匿名委托写法 委托的最后一个参数都为方法的返回值类型,剩下的都为方法的参数类型
 3         /// </summary>
 4         public void Init2()
 5         {
 6             //Func<T>
 7             //方式一
 8             //Func中的最后一个参数为委托封装的方法的返回值类型,前面剩下的为委托封装的方法的传入参数类型
 9             Func<int, int, string> factory = (int a, int b) => { return (a * b).ToString(); };
10             var cc = GetStr("", factory);
11             //方式二
12             var ss = GetVal("", (a, b) => { return a * b; });
13 
14         }
15 
16         /// <summary>
17         /// 返回一个int 类型的结果
18         /// </summary>
19         /// <param name="s"></param>
20         /// <param name="factory"></param>
21         /// <returns></returns>
22         private int GetVal(string s, Func<int, int, int> factory)
23         {
24             return factory(1, 3);
25         }
26 
27         /// <summary>
28         /// 返回一个string类型的结果
29         /// </summary>
30         /// <param name="s"></param>
31         /// <param name="factory"></param>
32         /// <returns></returns>
33         private string GetStr(string s, Func<int, int, string> factory)
34         {
35             return factory(1, 3);
36         }
复制代码

Action<>

复制代码
 1         /// <summary>
 2         /// Action<T> Action是可以有0~16个参数的无返回值委托
 3         /// </summary>
 4         public void Init1()
 5         {
 6             Action<int, int> factory = (int a, int b) => { Console.WriteLine(a * b); };
 7             var result = Create(factory);
 8         }
 9 
10         public int Create(Action<int, int> factory)
11         {
12             //参数逻辑处理
13             var arg1 = 4 * 5;
14             var arg2 = 3;
15             factory(arg1, arg2);
16             factory?.Invoke(arg1, arg2);
17             return 1;
18         }
复制代码

应用:

当在数据访问层不想定义实体来封装数据结果,就可以利用Func<T1, T2, TResult> 委托来处理

复制代码
  public IEnumerable<TResult> GetAllUser<TResult>(Func<User, Person, TResult> itemFactory)
  {
       var results = from u in _userRepository.GetAll()
                     join p in _personRepository.GetAll() on u.Id equals p.uId
                     select new { User = u, Person = p };
       IList<TResult> resultItems = new List<TResult>();
       foreach (var item in results.ToList())
       {
        resultItems.Add(itemFactory(item.User, item.Person));
       }
      return resultItems;
 }
复制代码

在应用层

 var query = userDao.GetAllUser((u, p) =>
            {
                return new { u.Id, u.LoginName, pId = p.Id, p.Name };
            });

在linq 的Select方法中也用了委托Func<>

复制代码
        //
        // 摘要:
        //     Projects each element of a sequence into a new form.
        //
        // 参数:
        //   source:
        //     A sequence of values to invoke a transform function on. 一个值序列,要对该序列调用转换函数
        //
        //   selector:
        //     A transform function to apply to each element. 应用于每个元素的转换函数
        //
        // 类型参数:
        //   TSource:
        //     The type of the elements of source.源元素的类型
        //
        //   TResult:
        //     The type of the value returned by selector.返回值的类型
        //
        // 返回结果:
        //     An System.Collections.Generic.IEnumerable`1 whose elements are the result of
        //     invoking the transform function on each element of source.
        //
        // 异常:
        //   T:System.ArgumentNullException:
        //     source or selector is null.
        public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);
复制代码
TSource表示传入参数的类型,TResult表示返回值的参数类型

调用处:

方式一

IEnumerable<CameraConfigDto> list = _cameraConfigRepository.GetAll().Where(c => c.EquipmentId == equipmentId).Select(new Func<CameraConfig, CameraConfigDto>(delegate (CameraConfig e)
            {
                return new CameraConfigDto() { };
            }));

方式二

 IEnumerable<CameraConfigDto> list = _cameraConfigRepository.GetAll().Where(c => c.EquipmentId == equipmentId).Select(delegate(CameraConfig e) {
                 return new CameraConfigDto() { };
            });

方式三

var list=_repository.GetAll().Where(c => c.EquipmentId == equipmentId).Select(delegate(CameraConfig e) {
                 return new CameraConfigDto() { };
            });

 

posted @   流年sugar  阅读(39)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示