Part 98 Anonymous methods in c#

What is an anonymous method?

Anonymous method is a method without a name. Introduced in C# 2.0,they provide us a way of creating delegate instances without having to write a separate method.

class Program
    {
        static void Main(string[] args)
        {
            List<Person> persons = new List<Person>() { 
                new Person{ID=101,Name="lin1"},
                new Person{ID=102,Name="lin2"},
                new Person{ID=103,Name="lin3"}
            };

            Person person = persons.Find(
                delegate(Person p)          //this is an anonymous method.
                {
                    return p.ID == 101;
                }
                );
            Console.WriteLine("person id={0},name={1}", person.ID, person.Name);

        }
    }
    class Person
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
View Code

Another example:Subscribing for an event handler.

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Button button = new Button();
            button.Text = "click me";
            this.Controls.Add(button);
            //button.Click += button_Click;
            button.Click += delegate(object send, EventArgs ea) {
                MessageBox.Show("you click me by anonymous method");
            };
        }

        void button_Click(object sender, EventArgs e)
        {
            MessageBox.Show("you just click me");
            throw new NotImplementedException();
        }
    }
View Code
posted @ 2015-09-12 02:53  Gester.Lin  阅读(153)  评论(0编辑  收藏  举报