Action委托
封装一个方法,该方法不具有参数并且不返回值
未使用Action委托:
使用Action委托:
使用Action委托写ForEach方法:
标准版:
简化版:
Func委托
封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
未使用Func委托:
使用Func委托:
Predicate委托
表示定义一组条件并确定指定对象是否符合这些条件的方法。
使用Predicate委托写FindAll方法:
案例(详细代码)
Frm-05
using Students.BLL;
using Students.Modal;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Students
{
public partial class Frm_05 : Form
{
StudentBLL studentBLL = new StudentBLL();
List<StudentModal> studentModalList = new List<StudentModal>();
public Frm_05()
{
InitializeComponent();
studentModalList = studentBLL.FindStudentsBySname(new StudentModal());
}
private void btn_Action_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
//studentModalList.ForEach(new Action<StudentModal>(delegate (StudentModal studentModal)
//{
// listBox1.Items.Add(studentModal);
//}));
MyAction myAction = new MyAction();
myAction.MyForEach<StudentModal>(studentModalList, listBox1);
}
private void btn_Func_Click(object sender, EventArgs e)
{
//var myStudent = new { Name = string.Empty, Age = 0 };
listBox1.Items.Clear();
//var newStudentModalList = studentModalList.Select<StudentModal, int>(new Func<StudentModal, int>(delegate (StudentModal studentModal)
//{
// if (studentModal.Sage > 10)
// {
// return studentModal.Sage;
// }
// return 0;
//})).ToList();
//MyAction myAction = new MyAction();
//myAction.MyForEach<int>(newStudentModalList, listBox1);
//MyClass
var newStudentModalList = studentModalList.Select<StudentModal, MyClass>(new Func<StudentModal, MyClass>(delegate (StudentModal studentModal)
{
if (studentModal.Sage > 10)
{
return new MyClass()
{
SName = studentModal.Sname,
Sage = studentModal.Sage,
Ssex = studentModal.Ssex
};