Part 98 Anonymous methods in c#

时间:2021-07-28 03:31:25

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();
}
}