委托
委托的定义
//使用delegate关键字,定义了一个委托类型,MyDel是类型名
//通过该类型前面的返回值以及参数来确定什么样的方法可以
//赋值给定以后的委托对象
delegate void MyDel(string s);
delegate int DInit(string s, int a);
委托的使用
delegate void MyDel(string s);
delegate int DInit(string s, int a);
class Person
{
//从方法的返回值以及方法的参数来判断方法是什么类型
public void CheseGreet(string name)
{
Console.WriteLine("早上好!"+name);
}
public static void EnglishGreet(string name)
{
Console.WriteLine("good moring "+name);
}
public int Init(string n ,int age)
{
return 0;
}
}
//================================================
static void Main (string[] arg)
{
Person p = new Person();
//委托是引用类型,把一个方法赋值给委托对象后
//委托对象和方法同事指向一个代码块,使用委托对象
//就是使用了给其赋值的方法
MyDel del = p.CheseGreet;
//一个委托对象同事存储了两个或两个以上的方法
//该委托称为多播委托
del += Person.EnglishGreet;
DInit init = p.Init;
//委托对象和使用原则和方法一样,都需要注意参数和返回值类型
del("lisi");
//委托存在的最大意义就是把方法当参数来传递
Tool.Fun(p.CheseGreet, "王八");
}
匿名委托和lambda表达式
delegate void DPrintArray(int[] a);
delegate bool DStringEqual(string s1, string s2);
class Tool
{
public static int Fun (Student x,Student y)
{
if (x.Age>y.Age)
{
return 1;
}
return 0;
}
}
//==========================================================
List<Student> stus = new List<Student>();
stus.Add(new Student("张三", 23));
stus.Add(new Student("李四", 20));
stus.Add(new Student("王五", 24));
//stus.Sort(Tool.Fun);
//匿名委托
stus.Sort(delegate (Student x,Student y) {
if (x.Age<y.Age)
{
return 1;
}
return 0;
});
//lambda表达式:()=>{}
del = (string s) =>
{
Console.WriteLine("google mingming " + s);
};
/*
stus.Sort((Student x, Student y) =>
{
if (x.Age < y.Age)
{
return 1;
}
return 0;
});
*/
foreach (var item in stus)
{
Console.WriteLine("{0},,{1}",item.Name,item.Age);
}
Fun 和Action 委托
//Fun和Action委托 都是泛型
//Fun委托一定要有返回值
Func<int> f = () => { return 0; };
Func<string, string, bool> f1 = (string s1, string s2) => { return s1 == s2; };
//Action 委托一定没有返回值
Action<int> act = (int i) =>
{
Console.WriteLine("{0}", i);
};