C#依頼とイベントの簡単な応用

2259 ワード

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
Computer's price is {0}!", priceManager.GetPrice())); //priceManager.GetPrice(); Console.WriteLine(string.Format("Invoke
Computer's price is {0}!", priceManager.GetPriceHandler.Invoke())); Console.WriteLine(); priceManager.GetPriceHandler = new PriceHandler(BookPrice); Console.WriteLine(string.Format("GetPrice
Book's price is {0}!", priceManager.GetPrice())); Console.WriteLine(string.Format("Invoke
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