参考资料:深入理解c#
委托1:https://blog.csdn.net/why070809123/article/details/102492612
一、概述
在上一篇博客里面已经叙述了委托的基础用法,本篇主要叙述委托的进一步用法,以及他是如何一步步变成lambda表达式的。
二、委托的变化过程
普通的委托应用:
delegate string delTest(string input);
public static string tes(string input)
{
string output = "输出" + input;
return output;
}
static void Main(string[] args)
{
delTest del = new delTest(tes);
}
我们需要提前写出方法,并将方法给到相应的委托,c#语言为了方便我们的代码编写工作,可以不用提前创建方法, 在实例化委托的时候给出临时的方法就可以了
匿名方法的应用:
delegate string delTest(string input);
static void Main(string[] args)
{
delTest del = delegate(string input) { string output = "输出" + input; return output; };
}
匿名方法的进一步变化:
delegate string delTest(string input);
static void Main(string[] args)
{
delTest del = (input) =>{ string output = "输出" + input; return output; };
}
继续变:
delegate string delTest(string input);
static void Main(string[] args)
{
delTest del = input => "输出" + input ;
}
三.委托变换(lambda表达式)的应用
应用代码:
class 测试
{
public delegate int nowDate(测试 obj);
public int agex = 10;
public int birthday = 2019;
public int getNowDage(nowDate i)
{
return i(this);
}
static void Main(string[] args)
{
测试 t1 = new 测试() { agex = 25, birthday = 1994 };
int age = t1.getNowDage((i) => i.birthday + i.agex);
Console.WriteLine(age);
}
}
结果:
lambda在c#源码中的应用:
得到list中所有的偶数:
List<int> intTestList = new List<int>() { 1, 2, 3, 4, 5,6,7,8,9,10 };
List<int> testResult = intTestList.Where((x1) => x1 % 2 == 0).ToList();
c#list.where 方法的源码:
public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
该方法为迭代器的扩展方法,List继承自迭代器所以可以调用。
public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
参数为Func的委托,同样看一下源码(这里用到泛型后面会进行详细讲解)
public delegate TResult Func<in T, out TResult>(T arg);
结合where方法及其调用可知,输入的为bool类型,输出为int类型的迭代,从而得到结果。
至于where方法中的委托使用细节就看不了了。。。