系统泛型委托(全)

一、Action委托(无返回值的系统委托)

public delegate void Action();//无参数无返回值

public delegate void Action<in T1>(T1 T);//该委托一共有十六个重载,in表示参数的数据类型;

假设有一person类

list<person> p=new list<person>(){

new person(){name="json",age=12},

new person(){name=".net",age=13},

new person(){name="jquery",age=15}

}

遍历list泛型集合

list.Foreach()//这里的参数需要一个Action且一个参数且参数的类型为person的委托

list.Foreach(new Action<person>(delegate(person p){匿名方法主体}));

list.Foreach(delegate(person p){匿名方法主体}));

2、Predicate泛型委托(返回值为bool类型的委托)

public bool predicate<in T>(T T1);

list.findAll()//参数为 predicate<person> p

list1=list.findAll(new predicate<person>(delegate(person p){return p.age>12}));//findAll()遍历整个list集合,分别将集合中的person对象一次给委托,当委托返回值为真时,将其添加到一个新的集合中,循环完毕后返回新的集合给list1

下面我们从写一下自己的list泛型集合的MyFindAll()扩展方法

namespace listNamespace(list泛型集合的命名空间)

public static class ListExtendMothed

{

  public List<T> MyFindAll<T>(this List<T> list,Predicate<T> predicate)//此处传predicate委托

  {

    List<T> newList=new List<T>();

    foreach(T item in list)

    {

      if(predicate(item))

      {

        newList.add(item);

      }

    }

  return newList;

  }

}

List<person> list=new List<person>(){....};

调用:list.MyFindAll<person>(delegate(person p){p.age>12})

三:Comparison泛型委托

public delegate int Comparison<in T>(T T1,T T2);

list.sort(delegate(person p1,person p2){return person1.age-person2.age})//实现年龄大小的排序

四:func泛型委托(重点)-自定义返回值类型,自定义传参类型

public delegate TResult Func<out TResult>();

public delegate TResult Func<in T,out TResult>()//共十七个重载

class person

{  

  public string name{set;get;}

  public int age{set;get;}

}

class personName

{

  public string name{set;get;}

}

List<person> list=new List<person>(){

new person(){name="json",age=12},

new person(){name="jquery",age=13}

}

list.select<T,S>()//参数为func委托:Func<person,TResult> func

list.select<person,personName>(new Func<person,personName>(delegate(person p){return new personName(){name=p.name}}))

下面我们为List写一个扩展方法实现select的方法

static class extend

{

  public static List<TR>MySelect<T,TR>(this List<T> list,Func<T,TR> func)

  {

    List<TR> list1=new List<TR>();

    foreach(T item in list)

    {

      list1.add(func(item));

    }

    retrun list1;

  }

}

使用:list.MySelect<person,personName>(delegate(person p){return new personName(){name=p.name}})

使用:var item=list.Select(delegate(person p){new {name=p.name}})

posted on 2013-12-13 09:07  无缘沙漠雨  阅读(250)  评论(0)    收藏  举报

导航