.NET 的扩展方法是在.NET 3.0引入的,MSDN给出的定义是:扩展方法使你能够向现有类型“添加”方法(包括你自定义的类型和对象噢),而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但是可以像扩展类型上的实例方法一样进行调用。对于用C#编写的客户端代码,调用扩展方法与调用在类型中实际定义的方法之间没有明显的差异。

看完上面的解释,有点摸不着头脑,我们在具体演示一下:

例子一:扩展Student类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace efdemo6
{
class Program
{
static void Main(string[] args)
{
Student st = new Student()
{
StudentName = "张三",
Score = ,
Birthday = DateTime.Parse("1990-1-1")
};
st.ShowStudent();//调用 扩展方法
}
}
//扩展学生类的功能
public static class ExStudent
{
//打印学生信息
public static void ShowStudent(this Student st)
{
Console.WriteLine("姓名:"+st.StudentName+" 分数:"+st.Score+" 生日:"+st.Birthday.ToString());
}
}
}

说明:我们为学生类添加一个功能,打印学生信息 ShowStudent。

注意:1.扩展方法只能定义在 非泛型的静态类中,使用 static修饰,参数使用this关键字 修饰要扩展的类,此处为Student类扩展方法, this Student st

执行结果:

如图:扩展方法的图标带有向下的箭头,且被标注为:扩展。

例子二 扩展List<T>泛型类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace efdemo6
{
class Program
{
static void Main(string[] args)
{
List<Student> list = new List<Student> {
new Student()
{
StudentName = "张三",
Score = ,
Birthday = DateTime.Parse("1990-1-1")
},
new Student()
{
StudentName = "李四",
Score = ,
Birthday = DateTime.Parse("1990-1-1")
}
}; Console.WriteLine("===排序前===");
foreach (var v in list)
{
Console.WriteLine(v.StudentName + " " + v.Score);
}
list.OrderBy();
Console.WriteLine("===排序后===");
foreach (var v in list)
{
Console.WriteLine(v.StudentName + " " + v.Score);
}
}
}
//扩展学生类的功能
public static class ExStudent
{
//扩展集合List 打印所有学生信息
public static void OrderBy(this List<Student> list)
{ list.Sort(new MyCompare());
} class MyCompare : IComparer<Student>
{
//比较学生的分数
public int Compare(Student st1, Student st2)
{
if (st1.Score > st2.Score) return ;
if (st1.Score == st2.Score) return ;
return -;
}
}
}
}

执行结果:

说明:此处定义了2个学生对象,张三 100分 李四 80分 ,并封装在List<Student>集合中,现在扩展一个OrderBy方法,按照学生分数排序。list.Sort() 方法传递一个 实现了IComparer<T>接口的实现类对象,并实现里面的Compare方法。

按F2查看Sort方法源代码:

可以看到,List<T>还有另一个sort方法,传递的是一个委托。

所以我们可以像下面这样写:

    //扩展学生类的功能
public static class ExStudent
{
public static void OrderBy(this List<Student> list)
{ list.Sort((x, y) =>
{
if (x.Score > y.Score) return ;
if (x.Score == y.Score) return ;
return -;
});
}
}

传递一个lamba表达式,运行结果相同。

.NET 扩展方法的更多相关文章

  1. .NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法

    .NET Core中间件的注册和管道的构建(3) ---- 使用Map/MapWhen扩展方法 0x00 为什么需要Map(MapWhen)扩展 如果业务逻辑比较简单的话,一条主管道就够了,确实用不到 ...

  2. .NET Core中间件的注册和管道的构建(2)---- 用UseMiddleware扩展方法注册中间件类

    .NET Core中间件的注册和管道的构建(2)---- 用UseMiddleware扩展方法注册中间件类 0x00 为什么要引入扩展方法 有的中间件功能比较简单,有的则比较复杂,并且依赖其它组件.除 ...

  3. 为IEnumerable<T>添加RemoveAll<IEnumerable<T>>扩展方法--高性能篇

    最近写代码,遇到一个问题,微软基于List<T>自带的方法是public bool Remove(T item);,可是有时候我们可能会用到诸如RemoveAll<IEnumerab ...

  4. C#的扩展方法解析

    在使用面向对象的语言进行项目开发的过程中,较多的会使用到“继承”的特性,但是并非所有的场景都适合使用“继承”特性,在设计模式的一些基本原则中也有较多的提到. 继承的有关特性的使用所带来的问题:对象的继 ...

  5. 扩展方法(C#)

    扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型.扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用. 下面的示例为String添加 ...

  6. 扩展方法解决LinqToSql Contains超过2100行报错问题

    1.扩展方法 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Sy ...

  7. C#扩展方法

    扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 扩展方法就相当于一个马甲,给一个现有类套上,就可以为这个类添加其他方法了. 马甲必须定义为stati ...

  8. 枚举扩展方法获取枚举Description

    枚举扩展方法 /// <summary> /// 扩展方法,获得枚举的Description /// </summary> /// <param name="v ...

  9. 扩展方法 1 简单的string扩展方法

    这里是关于 String的简单扩展方法 (静态类 静态方法 this 类型 这里是string) static class Program { static void Main(string[] ar ...

  10. C#中的扩展方法

    扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型.重新编译或以其他方式修改原始类型. 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用. 以上是msdn官网对扩展方 ...

随机推荐

  1. Ubuntu中查看32还是64

    安装ubuntu在pc上,不推荐在32位pc安装64位操作系统,64位pc安装32位操作系统 方法/步骤   1 按ctrl+shift+t 快捷键,打开终端,输入sudo uname --m ,按下 ...

  2. HDU 4251 --- 主席树(划分树是正解)

    题意:查询区间中位数 思路:模板题,相当于区间第K大的数,主席树可以水过,但划分树是正解.但还没搞明白划分树,先上模板 #include <iostream> #include <c ...

  3. PyCharm5.0.2最新版破解注册激活码(图文版)

    下载PyCharm http://download-cf.jetbrains.com/python/pycharm-professional-5.0.2.exe 安装PyCharm 设置激活服务器   ...

  4. hdu1018

    可以用斯特林公式直接求出n!的结果. 当n较小时公式已经很准确了,所以可以使用.但是,对于这种极限值为1的公式,只能用来估计位数,不能作为严格的等于的公式.类似的有素数分布定理  x/ln(x)~f( ...

  5. php Session存储到Redis的方法

    当然要写先安装php的扩展,可参考这篇文章:Redis及PHP扩展安装 修改php.ini的设置 复制代码 代码如下: session.save_handler = redis session.sav ...

  6. Inversion of Control Containers and the Dependency Injection pattern(转)

    In the Java community there's been a rush of lightweight containers that help to assemble components ...

  7. Nginx-Lua重定向系列

    Ningx Lua模块官方文档: 在Nginx中实现重定向可以通过rewrite指令,具体可参考<Nginx学习--http_rewrite_module的rewrite指令> 通过Lua ...

  8. PHP、JAVA、C#、Object-C 通用的DES加密

    PHP.JAVA.C#.Object-C 通用的DES加密 PHP: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 ...

  9. 分布式id 实现方式

    1. uuid 2. twitter的Snowflake 3. MongoDB ObjectID 4. Ticket Server 5. Instagram采用的方式(UUID方式)

  10. bzoj2515 Room

    Description Input Output 折半搜索,用散列表记录从原点出发,用了S(状压表示)这几种边(令|S|*2-1<=n),到达(x,y)的最大面积. #include<cs ...