匿名函数
匿名函数的意义
匿名函数就是没有名字的函数
匿名函数主要是配合委托和事件使用
//delegate (参数列表)
//{
//  函数逻辑
//};
//当函数中传递委托参数或者委托和事件赋值时使用匿名函数
//无参无返回值
//申明
Action a = delegate ()
{
    Console.WriteLine("匿名函数逻辑");
};
//调用
a();
//有参数
Action<int,string> b =delegate (int a ,string b)
{
    Console.WriteLine(a);
    Console.WriteLine(b);
};
b(1,"robot");
//有返回值
Func<int> c = delegate ()
{
    return 1;
};
class Test
{
    public Action action;
    public void Do(int a , Action fun)
    {
        Console.WriteLine(a);
        fun();
    }
    public Action GetFun()
    {
        return delegate()
        {
            Console.WriteLine("返回的匿名函数")
        };
    }
}
//作为参数传递
Test t = new Test();
t.Do(100,delegate()
{
    Console.WriteLine("随参数传入的匿名函数逻辑");
});
Action ac = delegate()
{
    Console.WriteLine("参数")
};
t.Do(50,ac);
//作为返回值
Action ac2 = t.GetFun();
ac2();
t.GetFun()();
//匿名函数添加到委托或者事件中之后无法单独移除
                    
                
                
            
        
浙公网安备 33010602011771号