今天学习委托时,偶然接触到了匿名函数,感觉挺新奇的,就把代码记录下来,以后有机会全面学习时再拿出来看看!
匿名函数是一个函数的简写,它没有函数名称。
我们把一个函数赋值给委托时,就可以使用匿名函数。
下面是简单例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 匿名函数 {
// 定义委托
public delegate void DelSayHi(string name);
class Program {
static void Main(string[] args) {
// 匿名函数 (函数的类型是什么取决于委托的定义)
DelSayHi del = delegate (string name) {
Console.WriteLine("你好!" + name);
}; // 这里需要写下分号 ;
del("张三");
del = delegate (string name) {
Console.WriteLine("hello" + name);
};
del("李四");
Console.ReadKey();
}
}
}
代码中,我们定义了一个void返回值,有一个string类型参数的委托;
然后我们定义委托时就是用到了匿名函数,将匿名函数赋值给该委托。
匿名函数有没有返回值类型取决于委托有没有。
最后直接通过委托调用函数。
运行截图:
再写一个例子
获取数组的最大值
代码:
/*匿名函数小例子*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 泛型 {
// 定义委托,实现两数相减
public delegate int Delegate(object o1, object o2);
class Program {
static void Main(string[] args) {
object[] arry1 = { 1, 2, 3, 5, 4, 6, 9, 8 };
object[] arry2 = { "asdfasdlg", "xzvcnryt", "waerw4thbvzxt", "asdfgh" };
// 匿名函数
object result = GetMax(arry1, delegate (object o1, object o2) {
return (int)o1 - (int)o2;
});
Console.WriteLine("最大值:" + result);
// 匿名函数
object result2 = GetMax(arry2, delegate (object o1, object o2) {
return o1.ToString().Length - o2.ToString().Length;
});
Console.WriteLine("最大值:" + result2);
Console.ReadKey();
}
// 获取数组的最大值
public static object GetMax(object[] arr, Delegate del) {
object max = arr[0];
for (int i = 0; i < arr.Length; i++) {
// 委托实现max减去arr[i],当小于0,说明max比它小
if (del(max, arr[i]) < 0) {
max = arr[i];
}
}
return max;
}
}
}
运行截图:
总结:
注意看匿名函数的定义,知道该怎么定义匿名函数就行了,具体他是用在哪方面,我也不知道,我猜测应该是用在一个函数只调用一次时,就使用匿名函数的方式取调用他吧。