@刘铁猛老师
委托的常用方法:用委托类型的参数将一个方法封装起来,再回调这个方法;
1.自定义委托
class Program
{
public delegate double Calc(double x, double y);//说明calc是个委托类,其对应方法的参数类型必须为double,返回值类型也是double
static void Main(string[] args)
{
Calculator calculator = new Calculator();
Calc calc1 = new Calc(calculator.Add);
double a = 100;
double b = 200;
double z = 0;
z = calc1(a, b);
Console.WriteLine(z); ;
}
}
class Calculator
{
public double Add(double x,double y)
{
return x + y;
}
}
输出为:300
2.
static void Main(string[] args)
{
Calculator calculator = new Calculator();
Action action = new Action(calculator.Report);//action代表委托(返回值为空),这里不可打括号,打括号代表调用;
calculator.Report();//调用Report方法
action.Invoke();//调用Report方法
action();//调用Report方法
Func<int, int, int> func1 = new Func<int, int, int>(calculator.Add);
//<>里的内容分别代表对应方法传入的参数类型和返回值类型;必须一致
int x = 100;
int y = 200;
int z = 0;
z = func1.Invoke(x, y);
Console.WriteLine(z); ; ;
}
}
class Calculator
{
public void Report()
{
Console.WriteLine("这是一个委托");
}
public int Add(int x,int y)
{
return x + y;
}
}
输出结果:
这是一个委托
这是一个委托
这是一个委托
300
3.同步调用:Invoke
隐式异步调用:BeginInvoke
显式异步调用:task
4.应适当使用接口来代替委托:
分割线分割线分割线分割线分割线分割线分割线分割线分割线分割线分割线
5.以下:dele1这个变量引用着一个Mydele类型的实例,这个实例里“包裹”着M1这个方法。
class Program
{
static void Main(string[] args)
{
Mydele dele1 = new Mydele(M1);
dele1();
}
static void M1()
{
Console.WriteLine("I'm so tired");
}
//声明一个新的委托类型Mydele,传入参数为空,返回值为空
delegate void Mydele();
}
输出为:I’m so tired
6.一个委托可以包裹两个方法:dele1包裹了stu1.sayHello与M1两个方法;
class Program
{
static void Main(string[] args)
{
Mydele dele1 = new Mydele(M1);
Student stu1 = new Student();
dele1 += stu1.sayHello;
dele1();
}
static void M1()
{
Console.WriteLine("I'm so tired");
}
//声明一个新的委托类型
delegate void Mydele();
}
class Student
{
public void sayHello()
{
Console.WriteLine("Hello");
}
}
输出为:I’m so tired
Hello
7.声明一个新的委托:传入参数为两个整型,返回值为整型;
//声明一个新的委托类型
delegate int Mydele(int a,int b);
static void Main(string[] args)
{
Calculator cal1 = new Calculator();
Mydele dele1 = new Mydele(cal1.Add);
int z = dele1(3, 4);
Console.WriteLine(z);
}
输出为:7
8.泛型委托:
9.action的新用法
class Program
{
static void Main(string[] args)
{
Student stu1 = new Student();
//action包裹一个传入参数为string类型的方法
Action<string> action = new Action<string>(stu1.sayHello);
action("TOM");
}
}
class Student
{
public void sayHello(string name)
{
Console.WriteLine($"Hello,{name}");
}
}
10.func的用法:
static void Main(string[] args)
{
Student stu1 = new Student();
Calculator cal1 = new Calculator();
var func = new Func<int, int, int>(cal1.Add);
int z = func(3, 4);
Console.WriteLine(z);
}
11.lambda表达式范例:
Func<int, int, int> func2 = new Func<int, int, int>((int a, int b) => { return a * b; });
int p = func2(3, 4);
Console.WriteLine(p);
还可以再简化:
Func<int, int, int> func2 = (int a, int b) => { return a * b; };
int p = func2(3, 4);
Console.WriteLine(p);
版权声明:本文为weixin_44413259原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。