BubbleSorter示例(匿名方法)

using System;
//using System.Threading;

namespace Ch12Ex03
{
    
delegate bool CompareOp(object lhs, object rhs);
    
class BubbleSorter
    
{

        
static public void Sort(object[] sortArray, CompareOp gtMethod)
        
{

            
for (int i = 0; i < sortArray.Length; i++)
            
{

                
for (int j = i + 1; j < sortArray.Length; j++)
                
{

                    
if (gtMethod(sortArray[j], sortArray[i]))
                    
{

                        
object temp = sortArray[i];

                        sortArray[i] 
= sortArray[j];

                        sortArray[j] 
= temp;

                    }


                }


            }


        }


    }


    
class Employee
    
{

        
private string name;

        
private decimal salary;



        
public Employee(string name, decimal salary)
        
{

            
this.name = name;

            
this.salary = salary;

        }




        
public override string ToString()
        
{

            
return string.Format(name + ", {0:C}", salary);

        }




        
public static bool RhsIsGreater(object lhs, object rhs)
        
{

            Employee empLhs 
= (Employee)lhs;

            Employee empRhs 
= (Employee)rhs;

            
return (empRhs.salary > empLhs.salary) ? true : false;

        }


    }





    
class MainEntryPoint
    
{

        
static void Main()
        
{

            Employee[] employees 
=

            
{

               
new Employee("Bugs Bunny"20000), 

               
new Employee("Elmer Fudd "10000),

               
new Employee("Daffy Duck"25000),

               
new Employee("Wiley Coyote", (decimal)1000000.38),

               
new Employee("Foghorn Leghorn"23000),

               
new Employee("RoadRunner'"50000)
            }
;

            CompareOp employeeCompareOp 
= new CompareOp(Employee.RhsIsGreater);

            BubbleSorter.Sort(employees, employeeCompareOp);



            
for (int i = 0; i < employees.Length; i++)

                Console.WriteLine(employees[i].ToString());
            Console.ReadKey();

        }


    }



}
 
發佈了144 篇原創文章 · 獲贊 1 · 訪問量 30萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章