C#常用的内置委托

时间:2023-12-22 17:40:26

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 内置委托
{
static class Program
{
static void Main(string[] args)
{
}

static List<Person> GetPersonList()
{
return new List<Person>() {
new Person (){ Age =1,Name ="小白01"},
new Person (){Age =2,Name ="小白02"},
new Person (){Age =3,Name ="小白03"}
};
}
#region 1、 Action
/// <summary>
/// 系统泛型委托--无返回值(用来传递无返回值方法)
/// </summary>
static void TestAction()
{
List<Person> list = GetPersonList();
list.ForEach(new Action<Person>(delegate(Person p) { Console.Write(p.Name + "&&" + p.Age); }));
//简写方式
list.ForEach(delegate(Person p) { Console.WriteLine(p.Name + "&&" + p.Age); });
}
#endregion

#region 2、系统泛型委托-Predicate 返回bool值
/// <summary>
/// 系统泛型委托-Predicate 返回bool值
/// </summary>
static void TestPredicate()
{
List<Person> list = GetPersonList();
list= list.FindAll(new Predicate<Person>(delegate(Person p) { return p.Age > 1; }));

//简写 ,使用findAll方法可以帮我们根据条件筛选出一个新的集合
list = list.FindAll(delegate(Person p ) {
return p.Age > 1;
});

List<Person> listNew = list.MyFindAll<Person>(delegate(Person p) { return p.Age > 1; });
}

//自己写的FindAll方法
static List<T> MyFindAll<T>(this List<T> list, Predicate<T> predicate)
{
List<T> newlist = new List<T>();
foreach (T item in list)
{
if (predicate(item))
{
newlist.Add(item);
}
}
return newlist;
}
#endregion

#region 3、比较委托返回值int
/// <summary>
///系统委托 Comparison
/// </summary>
static void TestComparison()
{
List<Person> list = GetPersonList();
list.Sort(delegate(Person x, Person y)
{

return x.Age - y.Age;
});
list.ForEach(delegate(Person p)
{
Console.WriteLine(p.Name + "," + p.Age);
});
}
#endregion

/// <summary>
/// 带自定义返回值的委托
/// </summary>
static void TestFunc()
{
List<Person> list = GetPersonList();
list.Select(new Func<Person,SmallPerson>(delegate(Person p){
return new SmallPerson() {Name =p.Name };
})); //映射

//简写
IEnumerable<SmallPerson>enuNew=list.Select((delegate(Person p)
{
return new SmallPerson() { Name = p.Name };
}));

List<SmallPerson> listnew = list.MySelect<Person, SmallPerson>(delegate(Person p) {
return new SmallPerson() {Name =p.Name };
});
}

static List<TR> MySelect<T, TR>(this List<T> list, Func<T, TR> func)
{
List<TR> listNew = new List<TR>();
foreach (T item in list)
{
//调用func委托将老集合元素转成另一个元素返回
TR re = func(item);
//将转换后的新元素,存入新集合
listNew.Add(re);
}
return listNew;
}
}
class SmallPerson
{
public string Name { get; set; }
}
}