zoukankan      html  css  js  c++  java
  • 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;
            }
        } 
    
    
    
    
    }
    


     

    该代码来自cnblogs  http://www.cnblogs.com/philzhou/archive/2012/04/05/2433663.html
  • 相关阅读:
    C语言寒假大作战01
    C语言I作业12—学期总结
    C语言I博客作业11
    C语言I博客作业10
    C语言I博客作业09
    C语言I博客作业08
    计算机组成与设计 复习
    概率论与数理统计 期末复习
    SPM(Software Project Management)课程感想
    Software Project Management_JUnit && Maven
  • 原文地址:https://www.cnblogs.com/voidobject/p/3975495.html
Copyright © 2011-2022 走看看