2017年1月2日 星期一

Extension Method

目的:
讓我們在不修改原始程式,為類別增加新函式。

  1. Enumerable.Range(1, 3)
  2. .Select(x => x * 2)
  3. .ToList()
  4. .ForEach(x => Console.WriteLine(x.ToString()));

Enumerable.Range() 產生 1、2、3
Select() 2、4、6
ForEach() 列印在畫面上

因為 List 才有 ForEach()
所以先 ToList()
再 ForEach()

這邊可以利用 Extension Method
幫 IEnumerable 打造一個 ForEach()


  1. namespace ConsoleApp
  2. {
  3. public static class Extensions
  4. {
  5. internal static void ForEacht>(this IEnumerablet source, Actiont action)
  6. {
  7. foreach (T element in source)
  8. action(element);
  9. }
  10. }
  11. }

整理一下
第一、第一個參數 this IEnumerable 特別加了 this 且 class 或 interface
第二、Extension Method 必須都為 static method


  1. Enumerable
  2. .Range(1, 3)
  3. .Select(x => x * 2)
  4. .ForEach(x => Console.WriteLine(x.ToString()));
  1. 用了 Extension Method 後這樣就能拿掉 ToList()
  1.  

沒有留言:

Visual Studio 2017/2019 推薦的擴充功能與更新

參考文章: 覺得 Google 的 Blogger 不太順手?透過 HTML 的 iframe 移花接木 HackMD