C# 委托与事件简单应用
C# 事件简单应用
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestIO { public delegate double PriceHandler(); public class PriceManager { public PriceHandler GetPriceHandler; //委托处理,当价格高于100元按8.8折计算,其他按原价计算 public double GetPrice() { //GetPriceHandler.GetInvocationList(); 按照此调用顺序,返回多路广播委托的调用列表 if (GetPriceHandler.GetInvocationList().Count() > 0) { if (GetPriceHandler() > 100) return GetPriceHandler() * 0.88; else return GetPriceHandler(); } return -1; } } class Program { static void Main(string[] args) { PriceManager priceManager = new PriceManager(); //调用priceManager的GetPrice方法获取价格 //直接调用委托的Invoke获取价格,两者进行比较 priceManager.GetPriceHandler = new PriceHandler(ComputerPrice); Console.WriteLine(string.Format("GetPrice\n Computer's price is {0}!", priceManager.GetPrice())); //priceManager.GetPrice(); Console.WriteLine(string.Format("Invoke\n Computer's price is {0}!", priceManager.GetPriceHandler.Invoke())); Console.WriteLine(); priceManager.GetPriceHandler = new PriceHandler(BookPrice); Console.WriteLine(string.Format("GetPrice\n Book's price is {0}!", priceManager.GetPrice())); Console.WriteLine(string.Format("Invoke\n Book's price is {0}!", priceManager.GetPriceHandler.Invoke())); Console.ReadKey(); } //书本价格为98元 public static double BookPrice() { return 98.0; } //计算机价格为8800元 public static double ComputerPrice() { return 8800.0; } } }
本文来自博客园,作者:至道中和,转载请注明原文链接:https://www.cnblogs.com/voidobject/archive/2012/09/23/3975495.html