• Delegate &&Lambda


    匿名函数及委托的使用:

     1 public delegate void NoReturnNoParaOutClass();//delegate can be defined in class or out of class
     2     public sealed class LambdaShow
     3     {
     4         public delegate void NoReturnNoPara();//1 委托的声明   委托是一种类型
     5         public delegate int WithReturnNoPara();
     6         public delegate void NoReturnWithPara(int id, string name);
     7         public delegate LambdaShow WithReturnWithPara(DateTime time);
     8         public delegate LambdaShow WithReturnWithParaRefOut(ref DateTime time, out int i);
     9 
    10         public void Show()
    11         {
    12             Student student = new Student()
    13             {
    14                 Id = 123,
    15                 Name = "Smith"
    16             };
    17             student.Study();
    18 
    19             {
    20                 NoReturnNoPara method = new NoReturnNoPara(this.DoNothing1);//2委托的实例化
    21                 method.Invoke();//3 委托实例的调用
    22                 method();
    23                 this.DoNothing1();
    24             }
    25             {
    26                 NoReturnWithPara method = new NoReturnWithPara(this.DoNothing);
    27                 //NoReturnWithPara method = this.DoNothing;
    28                 method.Invoke(123, "珍惜");
    29             }
    30             {
    31                 NoReturnWithPara method = new NoReturnWithPara(
    32                     delegate (int id, string name)//匿名方法
    33                     {
    34                         Console.WriteLine($"{id} {name} DoNothing out");
    35                     }
    36                     );
    37                 method.Invoke(123, "绚烂的夏");
    38             }
    39             {
    40                 NoReturnWithPara method = new NoReturnWithPara(
    41                      (int id, string name) =>//goes to  lambda表达式:匿名方法--方法
    42                     {
    43                         Console.WriteLine($"{id} {name} DoNothing out");
    44                     }
    45                     );
    46                 method.Invoke(123, "追梦");
    47             }
    48             {
    49                 NoReturnWithPara method = new NoReturnWithPara(
    50                      (id, name) =>//委托约束,去掉参数类型,自动推算
    51                      {
    52                          Console.WriteLine($"{id} {name} DoNothing out");
    53                      }
    54                     );
    55                 method.Invoke(123, "装逼的岁月");
    56             }
    57             {
    58                 NoReturnWithPara method = new NoReturnWithPara(
    59                      (id, name) => Console.WriteLine($"{id} {name} DoNothing out")
    60                      //方法体只有一行,就可以把大括号和分号去掉
    61                     );
    62                 method.Invoke(123, "美羡");
    63             }
    64             {
    65                 NoReturnWithPara method = (id, name) => Console.WriteLine($"{id} {name} DoNothing out");
    66                 //委托实例化的时候可以不要new NoReturnWithPara
    67                 method.Invoke(123, "晴月");
    68             }  
    69         }
    70 
    71         private void DoNothing(int id, string name)
    72         {
    73             //Console.WriteLine("{0} {1} DoNothing out",id, name);
    74             Console.WriteLine($"{id} {name} DoNothing out");
    75         }
    76 
    77         private void DoNothing1()
    78         {
    79             Console.WriteLine("DoNothing1");
    80         }
    81 
    82         private void DoNothing2()
    83         {
    84             Console.WriteLine("DoNothing2");
    85         }
    86     }
    87 }
    委托的简单介绍

     系统自带delegate...(来自System)

    Action 无返回值

     1 #region 程序集 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
     2 // C:Program Files (x86)Reference AssembliesMicrosoftFramework.NETFrameworkv4.5mscorlib.dll
     3 #endregion
     4 
     5 namespace System
     6 {
     7     //
     8     // 摘要:
     9     //     封装一个方法,该方法只有一个参数并且不返回值。 若要浏览此类型的.NET Framework 源代码,请参阅Reference Source。
    10     //
    11     // 参数:
    12     //   obj:
    13     //     此委托封装的方法的参数。
    14     //
    15     // 类型参数:
    16     //   T:
    17     //     此委托封装的方法的参数类型。
    18     public delegate void Action<in T>(T obj);
    19 }

    Func: 带返回值

     1 #region 程序集 mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
     2 // C:Program Files (x86)Reference AssembliesMicrosoftFramework.NETFrameworkv4.5mscorlib.dll
     3 #endregion
     4 
     5 using System.Runtime.CompilerServices;
     6 
     7 namespace System
     8 {
     9     //
    10     // 摘要:
    11     //     封装一个方法,该方法不具有参数,且返回由 TResult 参数指定的类型的值。
    12     //
    13     // 类型参数:
    14     //   TResult:
    15     //     此委托封装的方法的返回值类型。
    16     //
    17     // 返回结果:
    18     //     此委托封装的方法的返回值。
    19     [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
    20     public delegate TResult Func<out TResult>();
    21 }

    匿名类型 Var:

     1                     //1 只能声明局部变量,不能是字段、也不能是静态属性
     2                     //2 声明的时候必须被初始化;               
     3                     var model = new
     4                     {
     5                         Id = 1,
     6                         Name = "Alpha Go",
     7                         Age = 21,
     8                         ClassId = 2
     9                     };
    10 
    11                     Console.WriteLine(model.Id);
    12                     Console.WriteLine(model.Name);
    13                     //model.Name = "张伟东";//只读,不能更改。

    扩展方法:

     1 /// <summary>
     2     /// 扩展方法:就是在不修改类型封装前提下,给类型额外的扩展一个方法
     3     /// 
     4     /// 不能滥用,尤其是一些基类型-->object
     5     /// </summary>
     6     public static class ExtendShow
     7     {
     8         /// <summary>
     9         /// 扩展方法:静态类里的静态方法,第一个参数类型前面加上this
    10         /// </summary>
    11         /// <param name="iParameter"></param>
    12         /// <returns></returns>
    13         public static int ToInt(this int? iParameter) //int? 表示类型可null可int,常用于数据库。
    14         {
    15             return iParameter ?? -1;//if null return -1; else return itself.
    16         }
    17         
    18         
    19 
    20         public static void ExtendLambdaShow(this LambdaShow lambda, int iParameter, string sParameter)
    21         {
    22             Console.WriteLine($"LambdaShow=={iParameter}==={sParameter}");
    23         }
    24         /// <summary>
    25         /// 如果跟实例方法相同,优先实例方法
    26         /// </summary>
    27         /// <param name="lambda"></param>
    28         public static void Show(this LambdaShow lambda)
    29         {
    30             Console.WriteLine($"LambdaShow");
    31         }
    32 
    33 
    34         //不能滥用,尤其是一些基类型-->object
    35         public static void DoNothing(this object oParameter)
    36         { }

    Linq:(利用扩展方法,借助lambda表达式筛选)

      1 /// <summary>
      2         /// 准备数据
      3         /// </summary>
      4         /// <returns></returns>
      5         private List<Student> GetStudentList()
      6         {
      7             #region 初始化数据
      8             List<Student> studentList = new List<Student>()
      9             {
     10                 new Student()
     11                 {
     12                     Id=1,
     13                     Name="打兔子的猎人",
     14                     ClassId=2,
     15                     Age=35
     16                 },
     17                 new Student()
     18                 {
     19                     Id=1,
     20                     Name="Alpha Go",
     21                     ClassId=2,
     22                     Age=23
     23                 },
     24                  new Student()
     25                 {
     26                     Id=1,
     27                     Name="白开水",
     28                     ClassId=2,
     29                     Age=27
     30                 },
     31                  new Student()
     32                 {
     33                     Id=1,
     34                     Name="狼牙道",
     35                     ClassId=2,
     36                     Age=26
     37                 },
     38                 new Student()
     39                 {
     40                     Id=1,
     41                     Name="Nine",
     42                     ClassId=2,
     43                     Age=25
     44                 },
     45                 new Student()
     46                 {
     47                     Id=1,
     48                     Name="Y",
     49                     ClassId=2,
     50                     Age=24
     51                 },
     52                 new Student()
     53                 {
     54                     Id=1,
     55                     Name="小昶",
     56                     ClassId=2,
     57                     Age=21
     58                 },
     59                  new Student()
     60                 {
     61                     Id=1,
     62                     Name="yoyo",
     63                     ClassId=2,
     64                     Age=22
     65                 },
     66                  new Student()
     67                 {
     68                     Id=1,
     69                     Name="冰亮",
     70                     ClassId=2,
     71                     Age=34
     72                 },
     73                  new Student()
     74                 {
     75                     Id=1,
     76                     Name="",
     77                     ClassId=2,
     78                     Age=30
     79                 },
     80                 new Student()
     81                 {
     82                     Id=1,
     83                     Name="毕帆",
     84                     ClassId=2,
     85                     Age=30
     86                 },
     87                 new Student()
     88                 {
     89                     Id=1,
     90                     Name="一点半",
     91                     ClassId=2,
     92                     Age=30
     93                 },
     94                 new Student()
     95                 {
     96                     Id=1,
     97                     Name="小石头",
     98                     ClassId=2,
     99                     Age=28
    100                 },
    101                 new Student()
    102                 {
    103                     Id=1,
    104                     Name="大海",
    105                     ClassId=2,
    106                     Age=30
    107                 },
    108                  new Student()
    109                 {
    110                     Id=3,
    111                     Name="yoyo",
    112                     ClassId=3,
    113                     Age=30
    114                 },
    115                   new Student()
    116                 {
    117                     Id=4,
    118                     Name="unknown",
    119                     ClassId=4,
    120                     Age=30
    121                 }
    122             };
    123             #endregion
    124             return studentList;
    125         }
    GetStudentList()
     //
            // 摘要:
            //     基于谓词筛选值序列。
            //
            // 参数:
            //   source:
            //     System.Collections.Generic.IEnumerable`1 进行筛选。
            //
            //   predicate:
            //     用于测试每个元素是否满足条件的函数。
            //
            // 类型参数:
            //   TSource:
            //     中的元素的类型 source。
            //
            // 返回结果:
            //     System.Collections.Generic.IEnumerable`1 ,其中包含输入序列中满足条件的元素。
            //
            // 异常:
            //   T:System.ArgumentNullException:
            //     source 或 predicate 为 null。
            public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
    
    //在Func<TSource, bool> predicate中:TSource是输入参数类型,bool是输出参数类型. 
    
    //
        // 摘要:
        //     封装一个方法,该方法具有一个参数,且返回由 TResult 参数指定的类型的值。 若要浏览此类型的.NET Framework 源代码,请参阅Reference
        //     Source。
        //
        // 参数:
        //   arg:
        //     此委托封装的方法的参数。
        //
        // 类型参数:
        //   T:
        //     此委托封装的方法的参数类型。
        //
        //   TResult:
        //     此委托封装的方法的返回值类型。
        //
        // 返回结果:
        //     此委托封装的方法的返回值。
        [TypeForwardedFrom("System.Core, Version=3.5.0.0, Culture=Neutral, PublicKeyToken=b77a5c561934e089")]
        public delegate TResult Func<in T, out TResult>(T arg);
    View Code

    借助反编译工具查看源码(迭代器没搞清楚,以后补充

     1 // System.Linq.Enumerable
     2 /// <summary>Filters a sequence of values based on a predicate.</summary>
     3 /// <param name="source">An <see cref="T:System.Collections.Generic.IEnumerable`1" /> to filter.</param>
     4 /// <param name="predicate">A function to test each element for a condition.</param>
     5 /// <typeparam name="TSource">The type of the elements of <paramref name="source" />.</typeparam>
     6 /// <returns>An <see cref="T:System.Collections.Generic.IEnumerable`1" /> that contains elements from the input sequence that satisfy the condition.</returns>
     7 /// <exception cref="T:System.ArgumentNullException">
     8 ///         <paramref name="source" /> or <paramref name="predicate" /> is <see langword="null" />.</exception>
     9 [__DynamicallyInvokable]
    10 public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
    11 {
    12     if (source == null)
    13     {
    14         throw Error.ArgumentNull("source");
    15     }
    16     if (predicate == null)
    17     {
    18         throw Error.ArgumentNull("predicate");
    19     }
    20     if (source is Enumerable.Iterator<TSource>)
    21     {
    22         return ((Enumerable.Iterator<TSource>)source).Where(predicate);
    23     }
    24     if (source is TSource[])
    25     {
    26         return new Enumerable.WhereArrayIterator<TSource>((TSource[])source, predicate);
    27     }
    28     if (source is List<TSource>)
    29     {
    30         return new Enumerable.WhereListIterator<TSource>((List<TSource>)source, predicate);
    31     }
    32     return new Enumerable.WhereEnumerableIterator<TSource>(source, predicate);
    33 }
    public static IEnumerable Where(this IEnumerable source, Func<TSource, bool> predicate)源码
     1 /// <summary>
     2         /// IEnumerable是集合的初始接口
     3         /// </summary>
     4         /// <typeparam name="TSource"></typeparam>
     5         /// <param name="source"></param>
     6         /// <param name="predicate"></param>
     7         /// <returns></returns>
     8         public static IEnumerable<TSource> ElevenWhere<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
     9         {
    10             if (source == null)
    11             {
    12                 throw new Exception("source");
    13             }
    14             if (predicate == null)
    15             {
    16                 throw new Exception("predicate");
    17             }
    18 
    19             //常规情况下数据过滤
    20             List<TSource> studentListLessThan30 = new List<TSource>();
    21             foreach (var student in source)
    22             {
    23                 //if (item.Age < 30)
    24                 if (predicate(student))
    25                 {
    26                     studentListLessThan30.Add(student);
    27                 }
    28             }
    29             return studentListLessThan30;
    30         }
    模拟Where
     1             {
     2                 var list = studentList.ElevenWhere<Student>(s =>
     3                 {
     4                     Console.WriteLine("1234678");
     5                     return s.Age < 30;
     6                 });//linq
     7                 foreach (var item in list)
     8                 {
     9                     Console.WriteLine($"Name={item.Name} Age={item.Age}");
    10                 }
    11                 //linq to object
    12             }
    测试模拟的Where
     1 {
     2                 //查询运算符
     3                 var list = studentList.Where<Student>(s => s.Age < 30 && s.Name.Length > 3);//陈述句
     4                 foreach (var item in list)
     5                 {
     6                     Console.WriteLine("Name={0}  Age={1}", item.Name, item.Age);
     7                 }
     8             }
     9 
    10             {
    11                 //查询表达式
    12                 Console.WriteLine("********************");
    13                 var list = from s in studentList
    14                            where s.Age < 30 && s.Name.Length > 3
    15                            select s;
    16 
    17                 foreach (var item in list)
    18                 {
    19                     Console.WriteLine("Name={0}  Age={1}", item.Name, item.Age);
    20                 }
    21             }

     (不是Sql)

      1 #region linq to object Show
      2             {
      3                 Console.WriteLine("********************");
      4                 var list = studentList.Where<Student>(s => s.Age < 30)
      5                                      .Select(s => new
      6                                      {
      7                                          IdName = s.Id + s.Name,
      8                                          ClassName = s.ClassId == 2 ? "高级班" : "其他班"
      9                                      });
     10                 foreach (var item in list)
     11                 {
     12                     Console.WriteLine("Name={0}  Age={1}", item.ClassName, item.IdName);
     13                 }
     14             }
     15             {
     16                 Console.WriteLine("********************");
     17                 var list = from s in studentList
     18                            where s.Age < 30
     19                            select new
     20                            {
     21                                IdName = s.Id + s.Name,
     22                                ClassName = s.ClassId == 2 ? "高级班" : "其他班"
     23                            };
     24 
     25                 foreach (var item in list)
     26                 {
     27                     Console.WriteLine("Name={0}  Age={1}", item.ClassName, item.IdName);
     28                 }
     29             }
     30             {
     31                 Console.WriteLine("********************");
     32                 var list = studentList.Where<Student>(s => s.Age < 30)
     33                                      .Select(s => new
     34                                      {
     35                                          Id = s.Id,
     36                                          ClassId = s.ClassId,
     37                                          IdName = s.Id + s.Name,
     38                                          ClassName = s.ClassId == 2 ? "高级班" : "其他班"
     39                                      })
     40                                      .OrderBy(s => s.Id)
     41                                      .OrderByDescending(s => s.ClassId)
     42                                      .ThenBy(s => s.ClassId)//排序
     43                                      .Skip(2)//跳过  分页
     44                                      .Take(3)//获取数据
     45                                      ;
     46                 foreach (var item in list)
     47                 {
     48                     Console.WriteLine($"Name={item.ClassName}  Age={item.IdName}");
     49                 }
     50             }
     51             List<Class> classList = new List<Class>()
     52                 {
     53                     new Class()
     54                     {
     55                         Id=1,
     56                         ClassName="初级班"
     57                     },
     58                     new Class()
     59                     {
     60                         Id=2,
     61                         ClassName="高级班"
     62                     },
     63                     new Class()
     64                     {
     65                         Id=3,
     66                         ClassName="微信小程序"
     67                     },
     68                 };
     69             {
     70                 //inner join
     71                 var list = from s in studentList
     72                            join c in classList on s.ClassId equals c.Id
     73                            select new
     74                            {
     75                                Name = s.Name,
     76                                ClassName = c.ClassName
     77                            };
     78                 foreach (var item in list)
     79                 {
     80                     Console.WriteLine($"Name={item.Name},CalssName={item.ClassName}");
     81                 }
     82             }
     83             {
     84                 var list = studentList.Join(classList, s => s.ClassId, c => c.Id, (s, c) => new
     85                 {
     86                     Name = s.Name,
     87                     ClassName = c.ClassName
     88                 });
     89                 foreach (var item in list)
     90                 {
     91                     Console.WriteLine($"Name={item.Name},CalssName={item.ClassName}");
     92                 }
     93             }
     94             {//左连接   (只有左连接,无右连接)右连接就反过来
     95                 var list = from s in studentList
     96                            join c in classList on s.ClassId equals c.Id
     97                            into scList
     98                            from sc in scList.DefaultIfEmpty()
     99                            select new
    100                            {
    101                                Name = s.Name,
    102                                ClassName = sc == null ? "无班级" : sc.ClassName//c变sc,为空则用
    103                            };
    104                 foreach (var item in list)
    105                 {
    106                     Console.WriteLine($"Name={item.Name},CalssName={item.ClassName}");
    107                 }
    108                 Console.WriteLine(list.Count());
    109             }
    110             {
    111                 var list = studentList.Join(classList, s => s.ClassId, c => c.Id, (s, c) => new
    112                 {
    113                     Name = s.Name,
    114                     CalssName = c.ClassName
    115                 }).DefaultIfEmpty();//为空就没有了
    116                 foreach (var item in list)
    117                 {
    118                     Console.WriteLine($"Name={item.Name},CalssName={item.CalssName}");
    119                 }
    120                 Console.WriteLine(list.Count());
    121             }
    122             #endregion
    Linq to Object 投影
  • 相关阅读:
    linux中的find命令——查找文件名
    int main(int argc,char* argv[])详解
    VIM进阶学习之几种模式和按键映射
    Fortran编译多个文件(转载)
    Vimdiff---VIM的比较和合并工具
    两篇很牛的vim使用技巧
    程序员软件的罪恶:从不清楚地汇报事故原因
    Free symbol is Harmful
    return语言结构 VS. scala默认返回值
    踩过的“坑”: 命令行指定Java class path
  • 原文地址:https://www.cnblogs.com/anwser-jungle/p/8371747.html
Copyright © 2020-2023  润新知