c#之委托

利用委托和泛型实现冒泡排序

class BubbleSorter
    {
       static   public void Sort<T>(IList<T> sortArray,Func<T,T,bool> comparison)
       {
           bool swapped = true;
           do{
               swapped = false;
               for (int i = 0; i < sortArray.Count - 1; i++) {
                   if (comparison(sortArray[i + 1], sortArray[i])) {
                       T temp = sortArray[i];
                       sortArray[i] = sortArray[i + 1];
                       sortArray[i + 1] = temp;
                       swapped = true;
                   }
               }
           }
           while(swapped);
       }
    }
class Employee
    {
        public string Name { get;private set; }
        public decimal Salary { get;private set; }
        public Employee(string name, decimal salary)
        {
            this.Name = name;
            this.Salary = salary;
        }
        public override string ToString()
        {
            return string.Format("{0},{1:c}", Name, Salary);
        }
        public static bool CompareSalary(Employee e1, Employee e2)
        {
            return e1.Salary < e2.Salary;
        }
    }
Employee[] employees =
            {
            new Employee("Bugs Buhny",20000),
            new Employee("Elmer Fudd",10000),
            new Employee("Daffy Duck",25000),
            new Employee("Wile Coyote",1000000.38m ),
            new Employee("RoadRunner",5000)
            };
            BubbleSorter.Sort(employees, Employee.CompareSalary);
            foreach (var employee in employees)
            {
                Console.WriteLine(employee);
            }
            Console.Read();

Lambda表达式

Fun<string,string> test=param=>
{
    param+=mid;
return param;
}

Lambda表达式运算符”=>”的左边列出了需要的参数,Lambda运算符的右边定义了赋予lambda变量方法的实现代码

参数

1.如果只有一个参数,只要写出参数名

Func<string,string> oneParam=s=>String.Format("test:{0}",s.ToUpper());

因为委托定义了string参数,所以s就是string类型,string.format就会返回一个字符串

2.多个参数

如果委托使用多个参数,参数名要放在花括号中去

Func<double,double,double> test=(x,y)=>x*y;

多行代码

如果Lambda表达式中只有一条语句,在方法快内就不需要花括号和return语句,因为编译器会添加一条隐形的return语句

Func<double,double,double> test=(x,y)=>x*y;
Func<double,double,double> test=(x,y)=>
{
return x*y;
}

这也是正确的,

但是如果Lambda表达式中的实现代码中有很多条语句,就必须添加花括号和return语句

事件

作为约定,事件一般使用两个参数的方法,其中第一个参数是一个对象,包含事件的发送者,第二个参数提供事件的相关信息

原文地址:https://www.cnblogs.com/ilooking/p/4307938.html