c# 擴充套件方法學習
在看王清培前輩的.NET框架設計時,當中有提到擴充套件方法 .
開頭的一句話是:擴充套件方法是讓我們在不改變類原有程式碼的情況下動態地新增方法的方式,這給面向物件設計 模組設計帶來了質的提升
很明顯,擴充套件方法在框架設計或者平時碼程式碼中,是能夠提升我們整個架構的靈活性的
一..net自帶擴充套件方法和自定義擴充套件方法
在使用linq時就能夠使用到很多.net自帶的擴充套件方法,比如where select等等
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請求,在進行拼裝請求報文時,就會使用到鏈式程式設計
如下程式碼所示
以上程式碼就是使用了擴充套件方法進行鏈式程式設計,從而使得整個請求資訊可以在一句程式碼中體現出來
接下來,我們自己實現鏈式程式碼
public static class ContextExtension { public static RectangleContext SetLength(this RectangleContext context,int num) { RectangleContext.Config.Length = num; return context; } public static RectangleContext SetWideth(this RectangleContext context, int num) { RectangleContext.Config.Wideth = num; return context; } public static RectangleContext SetHeight(this RectangleContext context, int num) { RectangleContext.Config.Height = num; return context; } } publicclass RectangleContext { public static RectangleContext Config=new RectangleContext(); public int Length { get; set; } publicint Wideth { get; set; } publicint Height { get; set; } }
呼叫和執行結果
總結
1.使用擴充套件方法能在不修改原有型別的基礎下,動態新增方法,這使得整個框架更具有靈活性
2.在使用上下文資訊的時候,可以使用鏈式程式設計,使得呼叫時能夠在一句程式碼中完成所有屬性設定
3.擴充套件方法不能濫用.新增擴充套件方法應當使用最小影響原則,即儘量不要在父類使用擴充套件方法,比如object,這將影響效能