多播委托
using System;
namespace _005多播委托
{
class Program
{
public delegate void GetString();
static void Main(string[] args)
{
GetString get= Test1;
get += Test2;
get += Test3;
get += Test4;
get -= Test1;//不需要时,可以剪掉
get();//可以同时发布多个事件
}
public static void Test1()
{
Console.WriteLine("Test1");
}
public static void Test2()
{
Console.WriteLine("Test2");
}
public static void Test3()
{
Console.WriteLine("Test3");
}
public static void Test4()
{
Console.WriteLine("Test4");
}
}
}
匿名委托
delegate可以近似看成方法名
using System;
namespace _006匿名委托
{
class Program
{
static void Main(string[] args)
{
Action ac = delegate ()
{
Console.WriteLine("这是个无参无返回值的方法");
};
ac();
Func<int, int, bool> f = delegate (int num1, int num2)
{
return true;
};
f(10,20);
}
}
}
Lamda
格式是 ()=>{};
using System;
namespace _007Lamda
{
class Program
{
static void Main(string[] args)
{
Func<int, int, int> f = delegate (int num1, int num2) { return num1 + num2; };//匿名委托
Func<int, int, int> f1 = (int num1,int num2) => { return num1 + num2; };
Func<int, int, int> f2 = (num1,num2) => { return num1 + num2; };
Func<int, int, int> f3 = (num1,num2) => num1+num2;
//f,f1,f2,f3的含义是一样的
Console.WriteLine(f3(10,20));
Action<int> ac = (a) => { Console.WriteLine(a); };
ac(100);
}
}
}