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(); } } }
总结
系列完善中,请持续关注...
分类:
CLR via C# 技术内幕
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~