• 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
  • 相关阅读:
    Java 基本数据类型
    关于 Java 安装配置文件总结
    Day01
    关于自律!
    Java
    Java
    一年软件开发工作有感!
    如何解决文档复制时候禁止复制限制
    tensorflow tf.keras概述
    jupyter使用说明书
  • 原文地址:https://www.cnblogs.com/voidobject/p/3975495.html
Copyright © 2020-2023  润新知