zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    PowerBuilder 前景(转贴)
    利用Lucene.net搭建站内搜索(3)创建索引
    执行力差的五大原因
    js关于document和window对象_javascript教程
    HTML内部链接
    深入理解 __doPostBack (转帖)
    利用Lucene.net搭建站内搜索(4)数据检索
    a href=#与 a href=javascript:void(0) 的区别 打开新窗口链接的几种办法
    Javascript进阶 (转帖)
    windows通过VNC连接linux (Fedora 12)
  • 原文地址:https://www.cnblogs.com/gester/p/4870318.html
Copyright © 2011-2022 走看看