Linq快速入門——擴展方法
Linq為我們提供了許多擴展方法,方便我們對數據源進行操作(Where,Select...)。即使你不了解算法,也能使用Linq當回牛人。擴展方法本質并不是什么高深的技術,說白了就是一個Static靜態方法。
聲明擴展方法步驟:
- 創建一個名為MyHelper的類,約定了此類中的方法均是擴展方法。注意這個類必須是靜態類(Static)
- 擴展方法必須是Static靜態方法
- 第一個參數為待擴展的類型,前面標注this
- 如果MyHelper在一個類庫中,記得對其添加引用并using相關名稱空間
A simple example
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Linq { public static class 擴展方法Helper { public static string ToMyUpper(this string helper) { return "\""+helper.ToUpper() + "\""; } public static string Quoted(this string helper,string a,string b) { return a + helper + b; } public static bool IsNumber(this string helper) { int i; return int.TryParse(helper,out i); } public static string ToChineses(this bool helper) { return helper ? "真" : "假"; } public static int CreateMan(this Person helper) { Person one = new Person { Age=18,Name="Eyes"}; return one.Age; } } public class Person { public int Age { get; set; } public string Name { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Linq { class Program { static void Main(string[] args) { Person p = new Person(); Console.WriteLine(p.Name.IsNumber().ToChineses()); Console.ReadKey(); } } }
總結
系列完善中,請持續關注...

浙公網安備 33010602011771號