.net中的委托

using  System;
using  System.Collections.Generic;
using  System.Linq;
using  System.Text;
// 使用未命名委托来减少应用程序的复杂性
namespace  AnonymousDelegates
{
    
// 定义委托
     delegate   decimal  CalculateBonus( decimal  sales);
   
    
// 定义类
     class  Employee
    {
        
public   string  name;
        
public   decimal  sales;
        
public   decimal  bonus;
        
public  CalculateBonus calcalation_algorithm;
    }
    
class  MyTest
    {

        
static   void  Main( string [] args)
        {
            
decimal  multiplier  =   2 ;
            CalculateBonus standard_bonus 
=   new  CalculateBonus(CalculateStandarBonus);
            
// 匿名委托
            CalculateBonus enhanced_bonus  =   delegate ( decimal  sales) {  return  multiplier  *  sales  /   10 ; };

            Employee[] staff 
=   new  Employee[ 5 ];
            
for  ( int  i  =   0 ; i  <   5 ; i ++ )
            {
                staff[i] 
=   new  Employee();
            }

            staff[
0 ].name  =   " 111 " ;
            staff[
0 ].sales  =   100 ;
            staff[
0 ].calcalation_algorithm  =  standard_bonus;

            staff[
1 ].name  =   " 222 " ;
            staff[
1 ].sales  =   200 ;
            staff[
1 ].calcalation_algorithm  =  standard_bonus;

            staff[
2 ].name  =   " 333 " ;
            staff[
2 ].sales  =   300 ;
            staff[
2 ].calcalation_algorithm  =  standard_bonus;

            staff[
3 ].name  =   " 444 " ;
            staff[
3 ].sales  =   400 ;
            staff[
3 ].calcalation_algorithm  =  standard_bonus;

            staff[
4 ].name  =   " 555 " ;
            staff[
4 ].sales  =   500 ;
            staff[
4 ].calcalation_algorithm  =  enhanced_bonus;

            
foreach  (Employee person  in  staff)
            {
                PerformBonusCalculation(person);
            }

            
foreach  (Employee person  in  staff)
            {
                DisplayPersonDetails(person);
            }

            Console.ReadKey();

        }

        
public   static   decimal  CalculateStandarBonus( decimal  sales)
        {
            
return  sales  /   10 ;
        }

        
public   static   void  PerformBonusCalculation(Employee person)
        {
            person.bonus 
=  person.calcalation_algorithm(person.sales);
        }

        
public   static   void  DisplayPersonDetails(Employee person)
        {
            Console.WriteLine(person.name);
            Console.WriteLine(person.bonus);
            Console.WriteLine(
" ------------- " );
        }
    }
}


你可能感兴趣的:(.net)