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=,Name="lin1"},
new Person{ID=,Name="lin2"},
new Person{ID=,Name="lin3"}
}; Person person = persons.Find(
delegate(Person p) //this is an anonymous method.
{
return p.ID == ;
}
);
Console.WriteLine("person id={0},name={1}", person.ID, person.Name); }
}
class Person
{
public int ID { get; set; }
public string Name { get; set; }
}

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();
}
}
上一篇:MWeb 1.6 发布!Dark Mode、全文搜寻、发布到Wordpress、Evernote 等支持更新、编辑/预览视图模式等


下一篇:【Python】使用python的tornado配合html页面示例