C# for Beginner Part 98 to 100
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 CodeAnother 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 CodePart 99 Lambda expression in c#
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; } ); Person p1 = persons.Find(p=>p.ID==101);//using lambda expression Person p2 = persons.Find((Person p)=>p.ID==101);//you can also explicitly the input type but no required 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=> is called lambda operator and read as Goes To. Notice that with a lambda expression you don‘t have to use the delegate keyword explicitly and don‘t have to specify the input parameter type explicity. The parameter type is inferred(推倒出来). lambda expressions are more convenient to use than anonymous methods. lambda expressions are particularly helpful for writing LINQ query expressions.
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/67466.html