C#_delegate和事件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

//如果账户金额小于0 触发事件

namespace Starter
{
    public delegate int DeleageteClass(out DateTime start, out DateTime stop);

    class Program
    {
        static void Main(string[] args)
        {
            Bank account = new Bank();

            account.NSF += NSFHandler;  //绑定账户小于0时候的事件

            account.Deposit(500);
            account.WithDrawal(750);

            Console.ReadLine();
        }

        public static void NSFHandler(object o, BankEventArgs e)   //如果小于0时候的会发生的事件
        {
            Console.WriteLine("NSF Transaction");
            Console.WriteLine("Balance: "+e.Balance);
            Console.WriteLine("Transaction: "+ e.Transaction);
        }
    }

    public delegate void OverDrawn(object o,BankEventArgs e);

    public class Bank {

        public event OverDrawn NSF;  //定义委托事件的属性

        public decimal Deposit(decimal amountDeposit)
        {
            propBalance += amountDeposit;
            return propBalance;
        }

        public decimal WithDrawal(decimal amountWithdrawn)
        {
            decimal newBalance = propBalance - amountWithdrawn;
            if (newBalance < 0)
            {
                if (NSF != null)         
                {

                    //BankEventArgs 用于记录当前类相关信息,供事件调用
                    BankEventArgs args = new BankEventArgs(Balance,amountWithdrawn);
                    //事件调用 - 方法NSFHandler
                    NSF(this, args);
                }
            }
            return propBalance = newBalance;
            
        }

        private decimal propBalance=0;

        public decimal Balance
        {
            get
            {
                return propBalance;
            }
        }
    }


    public class BankEventArgs : EventArgs
    {
        public BankEventArgs(decimal amountBalance,decimal amountTransaction)
        {
            propTransaction = amountTransaction;
            propBalance = amountBalance;
        }

        private decimal propBalance;

        public decimal Balance
        {
            get {
                return propBalance;
            }
        }

        private decimal propTransaction;

        public decimal Transaction
        {
            get
            {
                return propTransaction;
            }
        }
    }
}


原文地址:https://www.cnblogs.com/MarchThree/p/3720448.html