委托可以很方便地实现对一个对象方法的扩展
PhotoFilters是一个类,有3个人方法:
public void ApplyBrightness(Photo photo){Console.WriteLine("亮度增加");}public void ApplyContrast(Photo photo){Console.WriteLine("对比度增加");}public void Resize(Photo photo){Console.WriteLine("图片放大");}
现在想要增加一个方法,使用委托:
var photo = Photo.load("phtot.jpg");
var filters = new PhotoFilters();
在PhotoProcessor类中定义委托
public class PhotoProcessor{public delegate void PhotoFilterHandler(Photo photo);public void Process(Photo photo, PhotoFilterHandler filterHandler){filterHandler(photo);photo.Save();}}
在main方法中使用委托
//先给一个委托赋初值
PhotoFilterHandler filterHandler = filters.ApplyBrightness;
//在把其它方法给委托,这样委托就指向了一组方法filterHandler += filters.ApplyContrast;filterHandler += filters.Resize;
//在main方法中声明一个扩展的方法
static void RedEyesRemovalFilter(Photo photo){Console.WriteLine("去除红颜");}
//将这个方法添加进委托filterHandler += RedEyesRemovalFilter;
//使用委托
var processor = new PhotoProcessor();processor.Process(photo, filterHandler);