C#委托理解
C#委托理解,看看就好千万别信
委托就是让别人替你办事。
把原本该自己处理的事情,交给别人处理,但是你要告诉别人怎么做。
1 委托人 (要能够告诉别人怎么做 如: 委托别人买东西,取快递)
2 被委托人 (要能够接受别人的委托,ps : 可以接受 看家的委托,代购物的委托,代取快递的委托)
----------------------------------------
这些都是被委托人能够接受的委托事件类型
示例代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DelegateDemo
{
class Program
{
static void Main(string[] args)
{
B b = new B(); // 委托人B
A a = new A(); //被委托人A
b.tellConsignee(a);// 通知被委托人要办的事
a.buySomthing(); //执行委托任务
b.byeConsignee(a);// //确认收货,告诉被委托人可以去接受下一个委托任务去了
Console.ReadKey();
}
}
}
public class B // 委托人B (要能够告诉别人怎么做)
{
public void tellConsignee(A a) // 通知被委托人要办的事。(告诉别人怎么做)
{
a.buyEvent += buy;
}
public void byeConsignee(A a) //相当于确认收货,告诉被委托人可以去接受下一个委托任务去了
{
a.buyEvent -= buy;
Console.WriteLine("给你好评");
}
private void buy(string somthing) // 买东西 (做法)
{
Console.WriteLine("去买" + somthing);
}
}
public class A //被委托人 (要能够接受别人的委托)
{
public delegate void Buy(string somthing);
public Buy buyEvent=null;
public void buySomthing()//执行委托任务
{
if (buyEvent != null)
{
buyEvent("玛莎拉蒂");
}
else
{
Console.WriteLine("没人委托我办事儿...");
}
}
}