首页 > 代码库 > C#创建委托实例

C#创建委托实例

using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace MyDelegate{    class Program    {        static void Main(string[] args)        {            List<User> users = GetUsers();             //1.传统方式实例化委托实例            users = users.OrderBy(new Func<User, int>(OrderType)).ToList();             //2.委托参数采用匿名函数代替函数名            users = users.OrderBy(new Func<User, int>(delegate(User user)            {                return user.Number;            })).ToList();             ////3.匿名函数直接创建委托实例            users = users.OrderBy(delegate(User user)            {                return user.Number;            }).ToList();             ////4.lambda表达式本质:用于创建委托的匿名函数            users = users.OrderBy(user => user.Number).ToList();              //输出            users.ForEach(x =>            {                Console.WriteLine("Number{0}:Name{1}:Age:{2}", x.Number, x.Name, x.Age);            });             //暂停            Console.Read();        }          /// <summary>        /// 排序方式        /// </summary>        /// <param name="arg"></param>        /// <returns></returns>        private static int OrderType(User user)        {            return user.Number;  //按照编号排序        }         private static List<User>  GetUsers()        {            List<User> users = new List<User>();            User user1 = new User(3, "张三", 19);            User user2 = new User(2, "李四", 27);            User user3 = new User(1, "王五", 12);            users.Add(user1);            users.Add(user2);            users.Add(user3);            return users;        }    }}