Linq快速入门——扩展方法
2013-07-04 06:52
344 查看
Linq为我们提供了许多扩展方法,方便我们对数据源进行操作(Where,Select...)。即使你不了解算法,也能使用Linq当回牛人。扩展方法本质并不是什么高深的技术,说白了就是一个Static静态方法。
声明扩展方法步骤:
创建一个名为MyHelper的类,约定了此类中的方法均是扩展方法。注意这个类必须是静态类(Static)
扩展方法必须是Static静态方法
第一个参数为待扩展的类型,前面标注this
如果[b]MyHelper在一个类库中,记得对其添加引用并using相关名称空间[/b]
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(); } } }
相关文章推荐
- Linq快速入门——扩展方法
- Linq快速入门——扩展方法
- Linq快速入门——扩展方法
- Linq快速入门——扩展方法
- [新手入门]快速学习 ADO.NET Entity Framework系列文章 #3 -- LINQ-to-SQL、EntitySQL、查询产生器方法(Query builder)三种语法
- Linq入门——什么是linq & 扩展方法
- Linq入门——什么是linq & 扩展方法
- 静态属性和静态方法 - C++快速入门21
- Apache HttpComponents Client 4.0快速入门/升级-2.POST方法访问网页
- 新人作者快速入门的最好方法都在这了
- Linq扩展方法之Aggregate 对序列应用累加器函数
- linq本质扩展方法+lambda表达式
- 本周ASP.NET英文技术文章推荐[09/23 - 09/29]:IIS 7.0、Facebook.NET、ASP.NET AJAX、ModalPopupExtender、扩展方法、LinqDataSource、ListView、Visual Studio
- Linq查询扩展方法
- C#编程(六十一)------------LINQ中的扩展方法
- 静态属性和静态方法2 - C++快速入门22
- Linq之扩展方法
- Windows游戏编程快速入门方法
- 静态属性和静态方法 - C++快速入门21
- Sunshine与linq扩展方法