
委托的使用
class Program{static void Main(string[] args){MyDele dele1 = new MyDele(M1);Student stu = new Student();dele1 += stu.SayHello;dele1.Invoke();}static void M1() {Console.WriteLine("M1 is called");}}class Student{public void SayHello(){Console.WriteLine("Hello,I'm a student!");}}delegate void MyDele();
class Program{static void Main(string[] args){MyDele dele1 = new MyDele(Add);int res = dele1(100, 200);Console.WriteLine(res);}static int Add(int x,int y) {return x + y;}}delegate int MyDele(int a,int b);
泛型委托
MyDele<int> deleAdd = new MyDele<int>(Add);int res = deleAdd(100, 200);Console.WriteLine(res);MyDele<double> deleMul = new MyDele<double>(Mul);double mulRes = deleMul(3.0, 5.0);Console.WriteLine(mulRes);Console.WriteLine(deleAdd.GetType().IsClass);}static int Add(int x,int y){return x + y;}static double Mul(double x,double y){return x * y;}}delegate T MyDele<T>(T a, T b);
运用类库直接委托不用声明
class Program{static void Main(string[] args){Action action = new Action(M1);action();Action<string> action2= new Action<string>(SayHello);action2("Tim");Func<int, int, int> func = new Func<int, int, int>(Add);int res = func(100, 200);Console.WriteLine(res);}static void M1(){Console.WriteLine("M1 is called!");}static void SayHello(string name){Console.WriteLine("Hello,{0}",name);}static int Add(int x,int y){return x + y;}static double Mul(double x,double y){return x * y;}}
Lambda表达式
class Program{static void Main(string[] args){Func<int, int, int> func = new Func<int, int, int>((int a, int b) => { return a + b; });int res = func(100, 200);Console.WriteLine(res);func = new Func<int, int, int>((int x, int y) => { return x * y});res = func(3, 4);Console.WriteLine(res);}}
class Program{static void Main(string[] args){Func<int, int, int> func = ((int a, int b) => { return a + b; });int res = func(100, 200);Console.WriteLine(res);func =((int x, int y) => { return x * y; });res = func(3, 4);Console.WriteLine(res);}}
泛型方法+泛型委托类参数+
class Program{static void Main(string[] args){// DoSomeCalc<int>((int a, int b)=>{ return a * b; }, 100, 200);DoSomeCalc(( a, b) => { return a * b; }, 100, 200);//100,200可以推断出来是整型,所以int可以省略}static void DoSomeCalc<T>(Func<T, T, T> func, T x, T y){T res=func(x, y);Console.WriteLine(res);}}
