C# for Beginner Part 98 to 100

來源:互聯網
上載者:User

標籤:

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

Part 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.

In most of the cases lambda expressions supersedes(替代) anonymous methods. To my knowlege, the only time I prefer to use anonymous methods over lambdas is, when we have to omit(省略) the parameter list when it‘s not used within the body.

Anonymous methods allow the parameter list to be omitted entirely when it‘s not used within the body,where as with lambda expressions this is not the case.

For example, with anonymous method notice that we have omitted the parameter list as we are not using them within the body

Button.Click += delegate{MessageBox.Show("hello world.");};

The above code can be rewritten using lambda expression as shown below.Notice that with lambda we cannot omit the parameter list.

Button.Click+=(sender,e)=>{MessegeBox.Show("hello world.");};Button.Click+=()=>{MessegeBox.Show("hello world.");};//if omit parameter list it will get a compilar error.

Part 100   Func delegate in c#

What is Func<T,TResult> in C#?

In simple terms,Func<T,TResult> is just generic delegate. Depending on the requirement,the type parameters(T and TResult) can be replaced with the corresponding(對應的) type arguments.

For example,Func<Employee,string> is a delegate that represents(代表) a function expecting(期待) Employee object as an input parameter and returns a string.

class Program    {        static void Main(string[] args)        {            List<Employee> employees = new List<Employee>() {                 new Employee{ID=101,Name="lin1"},                new Employee{ID=102,Name="lin2"},                new Employee{ID=103,Name="lin3"}            };            //Func<Employee, string> selector = e => "name=" + e.Name;            IEnumerable<string> employeeNames = employees.Select(e => "name=" + e.Name);            foreach (string name in employeeNames)            {                Console.WriteLine(name);            }        }    }    class Employee    {        public int ID { get; set; }        public string Name { get; set; }    }
View Code

What is the difference between Func delegate and lambda expression?

They‘re the same, just two different ways to write the same thing. The lambda syntax is newer, more concise(簡潔) and easy to write.

What if I have to pass two or more input parameters?

As of this recording there are 17 overloaded versions of Func, which enables us to pass variable number and type of input parameters. In the example below, Func<int,int,string> represents a function that expects 2 int input parameters and returns a string.

class Program    {        static void Main(string[] args)        {                       Func<int, int, string> funcDelegate = (num1, num2) => (num1 + num2).ToString();            string result = funcDelegate(10,20);            Console.WriteLine("sum="+result);        }    }

Finally, I completely learning the  C# language, go to bed, good night guy.

C# for Beginner Part 98 to 100

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.