C# 中的委托
2008-01-27 21:37
141 查看
C#特有的属性“委托”的本质就是像C/C++中的函数指针,回调函数那样。不过对于面对对象的C#语言来说委托的函数不是单独存在的,而是和其类实例化的对象相关联的。
1.创建C#的委托:
在C#中创建委托的格式: public delegate void OpDelegate(int First, int Second);
此时能与该委托匹配的方法为:static public void Subtact(int First, int Second){....}
public void Add(int First, int Second){...}
就是说委托是可以与静态方法或非静态方法共用的。
2.一个银行例子,透支的处理类就是用到委托
STEP1.先写一个用于透支处理的委托方法相关的透支处理类:
using System;
namespace MSPress.CSharpCoreRef.Bank
...{
/**//// <summary>
/// 下面的 withdrawal 方法, 提供有透支情况发生
/// 的委托方法
/// </summary>
public class OverdraftProtection
...{
public OverdraftProtection(decimal initialLoan)
...{
_availableLoan = initialLoan;
_currentLoan = 0;
}
public decimal AvailableLoan
...{
set ...{ _availableLoan = value; }
get ...{ return _availableLoan; }
}
public decimal CurrentLoan
...{
set ...{ _currentLoan = value; }
get ...{ return _currentLoan; }
}
/**//// <summary>
/// 与Withdrawal的实例共用的方法,用于管理帐户贷款情况
/// 透支会根据构造函数指定的固定数量给付
/// </summary>
/// <param name="debit">Attempted debit.</param>
/// <returns>True if successful, false if overdraft
/// loan amount exceeded.</returns>
public bool HandleDebit(decimal debit)
...{
if(debit > 0)
...{
if(debit <= _availableLoan)
...{
_availableLoan -= debit;
_currentLoan += debit;
}
else
return false;
}
return true;
}
/**//// <summary>
/// 可以透支的金额
/// </summary>
protected decimal _availableLoan;
/**//// <summary>
/// 当前透支的金额
/// </summary>
protected decimal _currentLoan;
}
}
STEP2.然后是创建应行的帐户类:
using System;
namespace MSPress.CSharpCoreRef.Bank
...{
public class Account //银行的帐户类
...{
public delegate bool DebitPolicy(decimal aWithdrawal); //定义透支委托方法
//帐户类的构造函数,第一个参数是开始帐户的数额
//第二个参数则为定义委托方法的委托签名,Account创建后
//将传递一个与该委托签名匹配的委托方法
public Account(decimal anInitialBalance, DebitPolicy aDebitPolicy)
...{
_balance = anInitialBalance;
_debitPolicy = aDebitPolicy;
}
public decimal Balance
...{
get
...{
return _balance;
}
}
public void Deposit(decimal aDeposit)
...{
if(aDeposit < 0)
throw new ArgumentOutOfRangeException();
_balance += aDeposit;
}
public bool Withdrawal(decimal aWithdrawal) //取款方法
...{
if(aWithdrawal < 0)
throw new ArgumentOutOfRangeException();
if(aWithdrawal < _balance)
...{
_balance -= aWithdrawal;
return true;
}
else
...{
// 如果没有借贷政策,就不允许透支.
if(_debitPolicy == null)
return false;
aWithdrawal -= _balance;
if(_debitPolicy(aWithdrawal))
...{
_balance = 0;
return true;
}
else
...{
return false;
}
}
}
protected DebitPolicy _debitPolicy;
protected decimal _balance;
}
}
STEP3.最后定义主函数类把他们都实例化:
using System;
namespace MSPress.CSharpCoreRef.Bank
...{
class BankApp
...{
static void Main(string[] args)
...{
//实例化用于透支处理类,透支金额为500
OverdraftProtection op = new OverdraftProtection(500);
//定义Account中的委托方法
Account.DebitPolicy policy;
//将实例化的对象op的HandleDebit与Account中的委托方法
//匹配
policy = new Account.DebitPolicy(op.HandleDebit);
//实例化我的帐户
Account myAccount = new Account(100, policy);
bool done = false;
do
...{
DisplayMenu();
string choice = Console.ReadLine();
switch(choice.ToLower())
...{
case "w":
HandleWithdrawal(myAccount);
break;
case "d":
HandleDeposit(myAccount);
break;
case "q":
done = true;
break;
default:
InvalidChoice(choice);
break;
}
CurrentBalance(myAccount, op);
}while(!done);
}
static void DisplayMenu()
...{
Console.WriteLine(" W) Withdraw");
Console.WriteLine("D) Deposit");
Console.WriteLine("Q) Quit");
Console.Write("->");
}
static void InvalidChoice(string choice)
...{
Console.WriteLine("{0} is not a valid choice.", choice);
}
static void HandleWithdrawal(Account anAccount)
...{
Console.Write("Withdrawal amount: ");
string request = Console.ReadLine();
decimal withdrawal = Convert.ToDecimal(request);
bool result = anAccount.Withdrawal(withdrawal);
if(result == true)
Console.WriteLine("Withdrawal of {0} was successful.", withdrawal);
else
Console.WriteLine("Withdrawal of {0} was not successful.", withdrawal);
}
static void HandleDeposit(Account anAccount)
...{
Console.Write("Deposit amount: ");
string request = Console.ReadLine();
decimal deposit = Convert.ToDecimal(request);
anAccount.Deposit(deposit);
}
static void CurrentBalance(Account anAccount, OverdraftProtection op)
...{
Console.WriteLine("Balance is {0}", anAccount.Balance);
Console.WriteLine("Available overdraft is {0}", op.AvailableLoan);
Console.WriteLine("Current overdraft loan is {0}", op.CurrentLoan);
}
}
1.创建C#的委托:
在C#中创建委托的格式: public delegate void OpDelegate(int First, int Second);
此时能与该委托匹配的方法为:static public void Subtact(int First, int Second){....}
public void Add(int First, int Second){...}
就是说委托是可以与静态方法或非静态方法共用的。
2.一个银行例子,透支的处理类就是用到委托
STEP1.先写一个用于透支处理的委托方法相关的透支处理类:
using System;
namespace MSPress.CSharpCoreRef.Bank
...{
/**//// <summary>
/// 下面的 withdrawal 方法, 提供有透支情况发生
/// 的委托方法
/// </summary>
public class OverdraftProtection
...{
public OverdraftProtection(decimal initialLoan)
...{
_availableLoan = initialLoan;
_currentLoan = 0;
}
public decimal AvailableLoan
...{
set ...{ _availableLoan = value; }
get ...{ return _availableLoan; }
}
public decimal CurrentLoan
...{
set ...{ _currentLoan = value; }
get ...{ return _currentLoan; }
}
/**//// <summary>
/// 与Withdrawal的实例共用的方法,用于管理帐户贷款情况
/// 透支会根据构造函数指定的固定数量给付
/// </summary>
/// <param name="debit">Attempted debit.</param>
/// <returns>True if successful, false if overdraft
/// loan amount exceeded.</returns>
public bool HandleDebit(decimal debit)
...{
if(debit > 0)
...{
if(debit <= _availableLoan)
...{
_availableLoan -= debit;
_currentLoan += debit;
}
else
return false;
}
return true;
}
/**//// <summary>
/// 可以透支的金额
/// </summary>
protected decimal _availableLoan;
/**//// <summary>
/// 当前透支的金额
/// </summary>
protected decimal _currentLoan;
}
}
STEP2.然后是创建应行的帐户类:
using System;
namespace MSPress.CSharpCoreRef.Bank
...{
public class Account //银行的帐户类
...{
public delegate bool DebitPolicy(decimal aWithdrawal); //定义透支委托方法
//帐户类的构造函数,第一个参数是开始帐户的数额
//第二个参数则为定义委托方法的委托签名,Account创建后
//将传递一个与该委托签名匹配的委托方法
public Account(decimal anInitialBalance, DebitPolicy aDebitPolicy)
...{
_balance = anInitialBalance;
_debitPolicy = aDebitPolicy;
}
public decimal Balance
...{
get
...{
return _balance;
}
}
public void Deposit(decimal aDeposit)
...{
if(aDeposit < 0)
throw new ArgumentOutOfRangeException();
_balance += aDeposit;
}
public bool Withdrawal(decimal aWithdrawal) //取款方法
...{
if(aWithdrawal < 0)
throw new ArgumentOutOfRangeException();
if(aWithdrawal < _balance)
...{
_balance -= aWithdrawal;
return true;
}
else
...{
// 如果没有借贷政策,就不允许透支.
if(_debitPolicy == null)
return false;
aWithdrawal -= _balance;
if(_debitPolicy(aWithdrawal))
...{
_balance = 0;
return true;
}
else
...{
return false;
}
}
}
protected DebitPolicy _debitPolicy;
protected decimal _balance;
}
}
STEP3.最后定义主函数类把他们都实例化:
using System;
namespace MSPress.CSharpCoreRef.Bank
...{
class BankApp
...{
static void Main(string[] args)
...{
//实例化用于透支处理类,透支金额为500
OverdraftProtection op = new OverdraftProtection(500);
//定义Account中的委托方法
Account.DebitPolicy policy;
//将实例化的对象op的HandleDebit与Account中的委托方法
//匹配
policy = new Account.DebitPolicy(op.HandleDebit);
//实例化我的帐户
Account myAccount = new Account(100, policy);
bool done = false;
do
...{
DisplayMenu();
string choice = Console.ReadLine();
switch(choice.ToLower())
...{
case "w":
HandleWithdrawal(myAccount);
break;
case "d":
HandleDeposit(myAccount);
break;
case "q":
done = true;
break;
default:
InvalidChoice(choice);
break;
}
CurrentBalance(myAccount, op);
}while(!done);
}
static void DisplayMenu()
...{
Console.WriteLine(" W) Withdraw");
Console.WriteLine("D) Deposit");
Console.WriteLine("Q) Quit");
Console.Write("->");
}
static void InvalidChoice(string choice)
...{
Console.WriteLine("{0} is not a valid choice.", choice);
}
static void HandleWithdrawal(Account anAccount)
...{
Console.Write("Withdrawal amount: ");
string request = Console.ReadLine();
decimal withdrawal = Convert.ToDecimal(request);
bool result = anAccount.Withdrawal(withdrawal);
if(result == true)
Console.WriteLine("Withdrawal of {0} was successful.", withdrawal);
else
Console.WriteLine("Withdrawal of {0} was not successful.", withdrawal);
}
static void HandleDeposit(Account anAccount)
...{
Console.Write("Deposit amount: ");
string request = Console.ReadLine();
decimal deposit = Convert.ToDecimal(request);
anAccount.Deposit(deposit);
}
static void CurrentBalance(Account anAccount, OverdraftProtection op)
...{
Console.WriteLine("Balance is {0}", anAccount.Balance);
Console.WriteLine("Available overdraft is {0}", op.AvailableLoan);
Console.WriteLine("Current overdraft loan is {0}", op.CurrentLoan);
}
}
相关文章推荐
- C# 中的委托和事件
- 【C#语言基础】--委托(Delegate)(一)
- C#中的委托和Lambda表达式
- C# 中的委托和事件
- C#之委托学习一
- C# 中的委托和事件 (详细)
- C# 委托总结
- C#中的委托和事件(很不错的一篇文章)
- 转C# 委托演变
- C#不是C++ 之 委托(Delegate)
- C#中的委托和事件
- 提问c# action<> func<> 这2个委托怎么用和理解
- c#的委托用法delegate
- 大白话系列之C#委托与事件讲解(二)
- C#之委托、事件、lambda
- C#控制台基础 action<int,string> 有参数,无返回值委托的用法示例
- C#中的委托和事件(续)
- C# 事件 委托 教程
- C# 中的委托和事件
- C# 中的委托和事件(转)