c#中的扩展方法学习笔记

2020-01-05 10:05:54丽君

where的扩展方法定义 


public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

Select的扩展方法定义


public static IEnumerable<TResult> Select<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector);

(1)自己实现where和select的扩展方法


// where自实现
 public static IEnumerable<TSource> ExtenSionWhere<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)
 {
  if (source == null)
  {
  throw new Exception(nameof(source));
  }
  if (predicate == null)
  {
  throw new Exception(nameof(predicate));
  }
  List<TSource> satisfySource = new List<TSource>();
  foreach (var sou in source)
  {
  if (predicate(sou))
  {
   satisfySource.Add(sou);
  }
  }
  return satisfySource;
 }

 
 // select 自实现
 public static IEnumerable<TResult> ExtenSionSelect<TSource, TResult>(this IEnumerable<TSource> source, Func<TSource, TResult> selector)
 {
  if(source==null)
  {
  throw new Exception(nameof(source));
  }
  if(selector==null)
  {
  throw new Exception(nameof(source));
  }

  List<TResult> resultList = new List<TResult>();
  foreach(var sou in source)
  {
  resultList.Add(selector(sou));
  }
  return resultList;
 }

(2)自实现where和select调用


static void Main(string[] args)
 {
  List<int> list = new List<int>() { 1, 2, 3, 4, 5, 6 };
  
  //常规写法
  var selectList = list.ExtenSionWhere(p => p > 3).ExtenSionSelect(p => p.ToString()).ToList();
 
  //自定义泛型委托写法
  Func<int, bool> whereFunc = (num) => num > 3;
  Func<int, string> selectFunc = (num) => num.ToString();
  var selectList1 = list.ExtenSionWhere(p => whereFunc(p)).ExtenSionSelect(p => selectFunc(p)).ToList();
 
 }

二.使用扩展方法实现链式编程

我在项目中经常使用开源的Flurl进行http请求,在进行拼装请求报文时,就会使用到链式编程