C# Programming Tips(1) : anonymous methods and delegate

    技术2022-05-11  98

     

    In versions of C# previous to 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods.

    Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. For example:

     

    public delegate int AddHandler(int a, int b); static void Main(string[] args) { //instantiate the delegate type using anonymous methods AddHandler p = delegate(int a, int b) { return a + b; }; //call from anonymous methods Console.WriteLine(p(10, 1)); //instantiate delegate type using named method p = new AddHandler(NamedMethods); //call from named methods Console.WriteLine(p(2,3)); //Creating anonymous methods is essentially a way to pass a code block as a delegate parameter Thread t = new Thread( delegate() { for (int i = 0; i < 10; i++) { Console.WriteLine(i-10); } }); t.Start(); //create and fill the collection List<Person> persons = new List<Person>(); persons.Add(new Person(2, "Benny Xu")); persons.Add(new Person(3, "Jim Tang")); persons.Add(new Person(1, "Tom Y")); persons.Add(new Person(4, "William XX")); Person targe; //anonymous methods used as parameter targe = persons.Find(delegate(Person person) { return person.ID == 1; }); //declare delegate Predicate<Person> predicate = delegate(Person q) { return q.ID == 4; }; targe = persons.Find(predicate); //sort list by ID desc persons.Sort(delegate(Person p1 ,Person p2) { if (p1.ID == p2.ID) { return 0; } else if (p1.ID < p2.ID) { return 1; } else { return -1; } }); //sort list by ID asc persons.Sort(delegate(Person p1, Person p2) { return Comparer<int>.Default.Compare(p1.ID, p2.ID); }); //sort by date time asc persons.Sort(delegate(Person p1, Person p2) { return Comparer<DateTime>.Default.Compare(p1.InDate, p2.InDate); }); Console.ReadLine(); } static int NamedMethods(int a, int b) { return a * b; } internal class Person { public int ID { get; set; } public string Name { get; set; } public DateTime InDate { get; set; } public Person(int id,string name) { ID = id; Name = name; InDate = DateTime.Now.AddDays(id * -1); } public override string ToString() { return string.Format("ID='{0}',Name='{1}','{2}' ",ID,Name,InDate); } }


    最新回复(0)