下面通过例子进行介绍:
class Program
{
static void Main(string[] args)
{
List<Employee> employees = Employee.GetEmployees();
//Action委托
//employees.ForEach
Action<Employee> empAction = new Action<Employee>(Employee.CalculateAge);
employees.ForEach(empAction);
foreach (var e in employees)
{
Console.WriteLine(e.Age);
}
//使用 Lambda表达式:
employees.ForEach(e => e.Age = DateTime.Now.Year - e.Birthday.Year);
//Func 委托: Enumerable.First<TSource> 方法
Func<Employee, bool> myFunc = new Func<Employee, bool>(Employee.NameIsEqual);
Console.WriteLine(employees.First(myFunc).FirstName);
//使用 Lambda表达式:
Console.WriteLine(employees.First(e => e.FirstName == "Jaliya").FirstName);
Console.ReadKey();
}
}
/// <summary>
/// 自定义 员工 类
/// </summary>
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime Birthday { get; set; }
public int Age { get; set; }
public static List<Employee> GetEmployees()
{
return new List<Employee>()
{
new Employee()
{
FirstName = "Jaliya",
LastName = "Udagedara",
Birthday = Convert.ToDateTime("1986-09-11")
},
new Employee()
{
FirstName = "Gary",
LastName = "Smith",
Birthday = Convert.ToDateTime("1988-03-11")
}
};
}
public static void CalculateAge(Employee emp)
{
emp.Age = DateTime.Now.Year - emp.Birthday.Year;
}
public static bool NameIsEqual(Employee emp)
{
return emp.FirstName == "Jaliya";
}
}
在主函数中,可以通过下面语句,获取一个List
List<Employee> employees = Employee.GetEmployees();
Action:
接收一个或多个输入参数,但不返回任何参数,可传递至多16种不同类型的参数类型。
例如List<T>.ForEach方法,接收一个类型为T的Action,例子如下,其中Employee是自定义类型
static void CalculateAge(Employee emp)
{
emp.Age = DateTime.Now.Year - emp.Birthday.Year;
}
可以创建一个Action,指向上面的方法:
Action<Employee> empAction = new Action<Employee>(CalculateAge);employees . ForEach ( empAction );
foreach (Employee e in employees)
{
Console.WriteLine(e.Age);
}
employees.ForEach(e => e.Age = DateTime.Now.Year - e.Birthday.Year);
Func<TResult>:
这种委托指向具有0、 1或多个输入参数,并返回TResult类型参数的方法。
以Enumeralbe.First<TSource>方法为例,该方法接收一个Func,并返回第一个满足条件的元素。
在这个例子中,this particular method accepts Func which accepts an Employee and returns a bool value.,因此我们需要创建一个方法,并用Func指向它。
static bool NameIsEqual(Employee emp)
{
return emp.FirstName == "Jaliya";
}
现在我们可以创建一个Func,并获取满足Func条件的Employee:
Func<Employee, bool> myFunc = new Func<Employee, bool>(NameIsEqual);
Console.WriteLine(employees.First(myFunc).FirstName);
同样,可以使用 Lambda 表达式简化代码:
Console.WriteLine(employees.First(e => e.FirstName == "Jaliya").FirstName);
Predicate<T>:
参考文章最开始的链接