125 lines
3.6 KiB
C#
125 lines
3.6 KiB
C#
|
|
namespace Lesson14_匿名函数
|
||
|
|
{
|
||
|
|
internal class Program
|
||
|
|
{
|
||
|
|
static void Main(string[] args)
|
||
|
|
{
|
||
|
|
#region 知识点一 什么是匿名函数
|
||
|
|
//顾名思义 就是没有名字的函数
|
||
|
|
//匿名函数的使用主要是配合委托和事件进行使用
|
||
|
|
//脱离委托和事件 是不会使用匿名函数的
|
||
|
|
#endregion
|
||
|
|
|
||
|
|
#region 知识点二 基本语法
|
||
|
|
//delegate (参数列表)
|
||
|
|
//{
|
||
|
|
// //函数体
|
||
|
|
// return 返回值;
|
||
|
|
//};
|
||
|
|
//何时使用?
|
||
|
|
//1.函数中传递委托参数时
|
||
|
|
//2.委托或事件赋值时
|
||
|
|
#endregion
|
||
|
|
|
||
|
|
#region 知识点三 使用
|
||
|
|
//注意:无法直接在函数中定义匿名函数,必须使用委托变量来接收匿名函数
|
||
|
|
//1.无参无返回
|
||
|
|
Action a = delegate ()//用一个无参无返回的委托变量 来接收匿名函数
|
||
|
|
{
|
||
|
|
Console.WriteLine("无参无返回匿名函数逻辑");
|
||
|
|
};
|
||
|
|
a(); //调用匿名函数
|
||
|
|
|
||
|
|
|
||
|
|
//2.有参
|
||
|
|
Action<int, string> a2 = delegate (int a, string b)
|
||
|
|
{
|
||
|
|
Console.WriteLine($"有参无返回的匿名函数逻辑,参数a:{a},参数b:{b}");
|
||
|
|
};
|
||
|
|
a2(10, "hello");
|
||
|
|
|
||
|
|
|
||
|
|
//3.有返回值
|
||
|
|
Func<int> f = delegate ()
|
||
|
|
{
|
||
|
|
Console.WriteLine("无参有返回值的匿名函数逻辑");
|
||
|
|
return 10;
|
||
|
|
};
|
||
|
|
Console.WriteLine(f());
|
||
|
|
|
||
|
|
|
||
|
|
//4.一般情况会作为函数参数传递 或者 作为函数返回值
|
||
|
|
Test t = new Test();
|
||
|
|
|
||
|
|
Action ac = delegate ()
|
||
|
|
{
|
||
|
|
Console.WriteLine("作为类成员变量的匿名函数逻辑");
|
||
|
|
};
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
//参数传递
|
||
|
|
t.Dosomething(100, delegate()
|
||
|
|
{
|
||
|
|
Console.WriteLine("作为参数传递的匿名函数逻辑");
|
||
|
|
});
|
||
|
|
t.Dosomething(200, ac);
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
//返回值
|
||
|
|
Action ac2 = t.GetFun();//可以先接收返回的匿名函数
|
||
|
|
ac2();//调用函数
|
||
|
|
|
||
|
|
//也可以直接调用返回的匿名函数
|
||
|
|
t.GetFun()();
|
||
|
|
#endregion
|
||
|
|
|
||
|
|
#region 知识点四 匿名函数的缺点
|
||
|
|
//添加到委托或事件中的匿名函数 无法被移除
|
||
|
|
Action ac3 = delegate ()
|
||
|
|
{
|
||
|
|
Console.WriteLine("匿名函数1");
|
||
|
|
};
|
||
|
|
|
||
|
|
ac3 += delegate ()
|
||
|
|
{
|
||
|
|
Console.WriteLine("匿名函数2");
|
||
|
|
};
|
||
|
|
ac3();//调用时 会依次调用两个匿名函数
|
||
|
|
//因为匿名函数没有名字 所以无法通过名字来移除
|
||
|
|
//ac3 -= ???
|
||
|
|
//所以只能通过清空委托变量来移除
|
||
|
|
#endregion
|
||
|
|
}
|
||
|
|
}
|
||
|
|
class Test
|
||
|
|
{
|
||
|
|
public Action action;
|
||
|
|
|
||
|
|
|
||
|
|
//作为函数参数传递匿名函数
|
||
|
|
public void Dosomething(int a,Action fun)
|
||
|
|
{
|
||
|
|
Console.WriteLine(a);
|
||
|
|
fun();
|
||
|
|
}
|
||
|
|
|
||
|
|
//作为函数返回值返回匿名函数
|
||
|
|
public Action GetFun()
|
||
|
|
{
|
||
|
|
return delegate ()
|
||
|
|
{
|
||
|
|
Console.WriteLine("作为返回值 函数内部返回的函数逻辑");
|
||
|
|
};
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// 总结
|
||
|
|
// 匿名函数 就是没有名字的函数
|
||
|
|
// 固定写法//delegate (参数列表){}
|
||
|
|
// 主要是在 委托传递和存储时 为了方便可以直接使用倪敏该函数
|
||
|
|
// 缺点是 没有办法指定移除
|
||
|
|
}
|