• 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
  • 相关阅读:
    蓝桥杯2016初赛
    蓝桥杯2016初赛
    蓝桥杯2016初赛
    蓝桥杯2015初赛
    关于VS本身遇到的一些相关问题
    VS的一些常用快捷键
    蓝桥杯2015初赛
    Luogu P1704 寻找最优美做题曲线
    POI2009 LYZ-Ice Skates
    Luogu P4313 文理分科
  • 原文地址:https://www.cnblogs.com/gester/p/4802478.html
Copyright © 2020-2023  润新知