C#委托详解(学习笔记)
程序员文章站
2022-06-08 10:20:54
...
C#委托详解
一、委托概述
1、什么是委托
- 委托是函数指针的“升级版”(实例:C/C++中的函数指针)
typedef int(*Calc)(int a,int b);
int x=200,y=100,z=0;
Calc funcPoint1=&Add;
Calc funcPoint2=⋐
z=funcPoint1(x,y);
z=funcPoint2(x,y);
- 一切皆地址
- 变量----->以某个地址为起点的一段内存中所存储的值
- 函数----->以某个地址为起点的一段内存中所存储的一组机器语言指令
- 调用方式
- 直接调用:函数名—>内存地址—>返回
- 间接调用:函数指针—>内存地址—>返回
class Program
{
static void Main(string[] args)
{
Calculator calc=new Calculator();
Action action = new Action(calc.Report);
action.Invoke();
//action();
Func<int, int, int> func1 = new Func<int, int, int>(calc.Add);
Func<int, int, int> func2 = new Func<int, int, int>(calc.Sub);
int x = 100, y = 200, z = 0;
z = func1.Invoke(x, y);
Console.WriteLine(z);
z = func2.Invoke(x, y);
Console.WriteLine(z);
}
}
class Calculator
{
public void Report()
{
Console.WriteLine("I have 3 methods");
}
public int Add(int a,int b)
{
return a + b;
}
public int Sub(int a,int b)
{
return a - b;
}
}
二、委托的声明
1、自定义委托
- 委托也是一种类,因此也可声明变量,创建实例
- 委托的声明格式有别于普通的类,主要为了照顾可读性以及C/C++传统
格式:访问级别+delegate(关键字)+函数返回值类型+委托名+(函数形参);
public delegate double Calc(double x, double y);
三、委托的使用
1、模板方法
"借用"指定的外部方法来产生结果(方法调用委托)
方法—>委托提供参数—>返回值
class Product
{
public string Name { get; set; }
}
class Box
{
public Product Product { get; set; }
public override string ToString()
{
return "Pruduct:"+Product.Name;
}
}
class WrapFactory
{
public Box WrapProduct(Func<Product> getProduct)
{
Box box = new Box();
Product product = getProduct.Invoke();
box.Product = product;
return box;
}
}
class ProductFactory
{
public Product MakePizza()
{
Product product = new Product();
product.Name = "pizza";
return product;
}
public Product MakeToyCar()
{
Product product = new Product();
product.Name = "toy car";
return product;
}
}
class Program
{
static void Main(string[] args)
{
ProductFactory productFactory = new ProductFactory();
WrapFactory wrapFactory = new WrapFactory();
Func<Product> func1 = new Func<Product>(productFactory.MakePizza);
Func<Product> func2 = new Func<Product>(productFactory.MakeToyCar);
Box box1 = wrapFactory.WrapProduct(func1);
Box box2 = wrapFactory.WrapProduct(func2);
Console.WriteLine(box1.ToString());
Console.WriteLine(box2.ToString());
}
}
2、回调方法
调用指定的外部方法(一般方法无返回值)
public Box WrapProduct(Func<Product> getProduct, Action<Product> logCallback)
{
Box box = new Box();
Product product = getProduct.Invoke();
if (product.Price>50)
{
logCallback(product);
}
box.Product = product;
return box;
}
static void Main(string[] args)
{
Logger logger = new Logger();
Action<Product> action1 = new Action<Product>(logger.Log);
Action<Product> action2 = new Action<Product>(logger.Log);
wrapFactory.WrapProduct(func1, action1);
wrapFactory.WrapProduct(func2, action2);
}
注:委托的缺点:
- 方法的耦合性增强
- 可读性下降、debug的难度增加
- 使用不当会造成内存泄露、性能下降
3、多播委托
一个委托的内部封装了不止一个方法
static void Main(string[] args)
{
Student student1 = new Student(1,ConsoleColor.Yellow);
Student student2 = new Student(2,ConsoleColor.Red);
Student student3 = new Student(3,ConsoleColor.Blue);
Action action1 = new Action(student1.DoHomework);
Action action2 = new Action(student2.DoHomework);
Action action3 = new Action(student3.DoHomework);
action1.Invoke();
action2.Invoke();
action3.Invoke();
action1 += action2;
action1 += action3;
action1.Invoke();
}
class Student
{
public int ID { get; set; }
public ConsoleColor PenColor { get; set; }
public Student()
{ }
public Student(int id,ConsoleColor penColor)
{
this.ID = id;
this.PenColor = penColor;
}
public void DoHomework()
{
Console.ForegroundColor = PenColor;
for (int i = 0; i < 5; i++)
{
Console.WriteLine("Student {0} doing homework {1} hour(s).",ID,i);
Thread.Sleep(1000);
}
}
}
注:多播委托执行过程按照封装的顺序依次执行
4、隐式异步调用
1、同步调用与异步调用
同步:按照顺序依次进行
异步:同时进行
注:串行同步单线程,并行异步多线程
2、隐式多线程 v.s. 显式多线程
- 直接同步调用:使用方法名
- 间接同步调用:使用单播/多播委托调用
- 隐式同步调用:使用委托的BeginInvoke
- 显示异步调用:使用Thread或Task
Console.WriteLine("直接同步调用\n------------------------");
Student stu1 = new Student(1, ConsoleColor.Red);
Student stu2 = new Student(2, ConsoleColor.Yellow);
Student stu3 = new Student(3, ConsoleColor.Blue);
stu1.DoHomework();
stu2.DoHomework();
stu3.DoHomework();
for (int i = 0; i < 10; i++)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.WriteLine($"Main Thread {i}.");
Thread.Sleep(500);
}
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("间接同步调用\n------------------------");
Action action1 = new Action(stu1.DoHomework);
Action action2 = new Action(stu2.DoHomework);
Action action3 = new Action(stu3.DoHomework);
action1 += action2;
action1 += action3;
action1.Invoke();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("隐式异步调用\n------------------------");
action1.BeginInvoke(null, null);
action2.BeginInvoke(null, null);
action3.BeginInvoke(null, null);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("显式异步调用\n------------------------");
Thread thread1 = new Thread(new ThreadStart(stu1.DoHomework));
Thread thread2 = new Thread(new ThreadStart(stu2.DoHomework));
Thread thread3 = new Thread(new ThreadStart(stu3.DoHomework));
lock(new Object()) {
thread1.Start();
thread2.Start();
thread3.Start();
}
Task task1 = new Task(new Action(stu1.DoHomework));
Task task2 = new Task(new Action(stu2.DoHomework));
Task task3 = new Task(new Action(stu3.DoHomework));
task1.Start();
task2.Start();
task3.Start();
5、接口代替委托
interface IProductFactory
{
Product Make();
}
class BallFactory : IProductFactory
{
public Product Make()
{
Product product = new Product();
product.Name = "balls";
product.Price = 12;
return product;
}
}
class Program
{
public static void Main(string[] args)
{
//...
WrapFactory wrapFactory = new WrapFactory();
Box box=wrapFactory.WrapProduct(new BallFactory());
Console.WriteLine(box);
}
}
下一篇: C语言学习6:函数详解