C# 扩展方法
扩展方法 使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。
当我们vs中编写代码使用Linq 的时候,经常会看到智能提示出现带如下符号的方法:
这就是扩展方法。
如何定义自己的扩展方法呢?MSDN给出了详细的解释(具体可以参阅 实现和调用自定义扩展方法):
1、定义一个静态类以包含扩展方法。该类必须对客户端代码可见。
2、将该扩展方法实现为静态方法,并使其至少具有与包含类相同的可见性。
3、该方法的第一个参数指定方法所操作的类型;该参数必须以 this 修饰符开头。
4、在调用代码中,添加一条 using 指令以指定包含扩展方法类的命名空间。
5、按照与调用类型上的实例方法一样的方式调用扩展方法。
下面来举两个小例子来说明一下扩展方法的定义和调用:
1、首先看一个最简单的,来为String 类 定义一个扩展方法:
public static class MehtondExtension { public static string tostring(this string s) { return (string.Format("Extension output: {0}", s)); } }
注意 类的定义和方法的定义都有static 修饰,方法的第一个参数有 this 修饰符
在Main函数中进行调用:
class Program { static void Main(string[] args) { string s = "Hello World"; Console.WriteLine(s.ExToString()); Console.ReadKey(); } }
结果输出 :Extension output: Hello World
2、来个略微复杂一点的,我们为一个集合添加一个查询的扩展方法,当然用linq可以更直接,这里举例只是为了说明扩展方法的使用:
//学生类 public class Student { public string Name { get; set; } public int Age { get; set; } public string City { get; set; } } //集合类 public class StudentList:List<Student> { public StudentList() { this.Add(new Student() { Name = "张三", Age = 22, City = "北京" }); this.Add(new Student() { Name = "李四", Age = 23, City = "北京" }); this.Add(new Student() { Name = "王武", Age = 24, City = "南京" }); this.Add(new Student() { Name = "何二", Age = 25, City = "南京" }); } } //扩展方法 //根据城市名称返回学生列表 public static class StuListExtension { public static IEnumerable<Student> GetStudentByCity(this List<Student> stuList, string city) { var result = stuList.Where(s => s.City == city).Select(s => s); return result; } }
在Main函数中进行调用:
class Program { static void Main(string[] args) { StudentList StudentSource = new StudentList(); IEnumerable<Student> bjStudents = StudentSource.GetStudentByCity("北京"); Console.WriteLine("北京的学生列表:"); foreach (var s in bjStudents) { Console.WriteLine(string.Format("姓名:{0} 年龄:{1} 城市:{2}", s.Name, s.Age, s.City)); } Console.ReadKey(); } }
结果显示:
作者:Rising Sun
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
分类:
C# 基础补遗
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?