C# 扩展方法

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

.Net 框架的扩展方法观摩

最常见的扩展方法是LINQ标准查询运算符,它将查询功能添加到现有的 System.Collections.IEnumerable和System.Collections.Generic.IEnumerable 类型。

在对List做一些筛选时大都会用到Where方法,例如:

List<int> list = new List<int>() { 10, 45, 15, 39, 21, 26 };
var result = list.Where(x => x > 15);

但查看List类时,发现没有where方法,而且这时必需要引命名空间:

using System.Linq; 

而且where方法就是Enumerable类里面的,这里的where就是一个IEnumerable的扩展方法

namespace System.Linq
{
    public static class Enumerable
    {
        //。。。。。其他省略
        public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);
    }
}
定义和调用扩展方法
  1. 定义包含扩展方法的静态类。
  2. 将扩展方法实现为静态方法,并且使其可见性至少与所在类的可见性相同。
  3. 此方法的第一个参数指定方法所操作的类型;此参数前面必须加上 this 修饰符。
  4. 在调用代码中,添加 using 指令,用于指定包含扩展方法类的命名空间。
  5. 和调用类型的实例方法那样调用这些方法。

就是在一个静态类里定义一个静态方法,这个方法的第一个参数要用this修饰,这方法是对其第一个参数进行扩展的方法。扩展方法要对那个对象扩展,该对象就是这个方法的第一个参数,并用this修饰

示例
using System.Linq;
using System.Text;
using System;

namespace CustomExtensions
{
    public static class StringExtension
    {
        public static int WordCount(this String str)
        {
            return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }
}
namespace Extension_Methods_Simple
{
    using CustomExtensions;
    class Program
    {
        static void Main(string[] args)
        {
            string s = "The quick brown fox jumped over the lazy dog.";
            int i = s.WordCount();
            //int i = StringExtension.WordCount(s);//也可以写成这样
            System.Console.WriteLine("Word count of s is {0}", i);
        }
    }
}
总结

因为扩展方法会会污染原有的类,所以在定义时要用命名空间来区分,就像不引用System.Linq,list就没有where方法。

参考

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/extension-methods#see-also

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/classes-and-structs/how-to-implement-and-call-a-custom-extension-method

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值