C#_delegate和事件 - 如果金额小于0则触发事件

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;
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值