C#学习笔记(八):扩展方法

还记得第一次使用DOTween时,发现缓动方法竟然是可以直接用Transform对象中调用到,当时就被震撼到了(那是还是C#小白一只)。好了不多说了,今天来学习一下C#的这个特性——扩展方法。

扩展方法简介

扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。

这样我们可以方便的扩展对象方法而无需使用继承,同时也可以给密封类添加方法。

我们来看一个例子:

 1 using System;
 2 
 3 namespace Study
 4 {
 5     class Program
 6     {
 7         private static void Main(string[] args)
 8         {
 9             int[] ints = { 10, 45, 15, 39, 21, 26 };
10             var result = ints.OrderBy(g => g);
11             foreach (var i in result)
12             {
13                 System.Console.Write(i + " ");
14             }
15 
16             Console.Read();
17         }
18     }
19 }

上面的代码会报错:找不到OrderBy方法,因为int类型的数组就没有这个方法。如果我们导入Linq的包后就可以使用了,如下:

using System.Linq;

原因就是OrderBy是Linq提供的一个扩展方法,是我们可以任意的添加指定类的公共方法。

扩展方法编写

我们要添加一个扩展方法,需要添加一个静态类,如下我们添加一个扩展string的方法,通过该方法我们可以获取字符串的单词数量。

 1 using System;
 2 
 3 namespace Study
 4 {
 5     class Program
 6     {
 7         private static void Main(string[] args)
 8         {
 9             string str = "Hi! My name is LiLei!";
10             Console.WriteLine(str.WordCount());
11 
12             Console.Read();
13         }
14     }
15 
16     public static class MyExtensions
17     {
18         public static int WordCount(this String str)
19         {
20             return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length;
21         }
22     }
23 }

运行程序输出“5”。

扩展方法编写要点

  1. 扩展方法必须在一个非嵌套、非泛型的静态类中定义;
  2. 必须有一个以this关键字加上类型的参数,该参数表示扩展该类型的方法,同时将该类型的值作为参数传递进来;
  3. 第一个参数不能使用out和ref修饰符;
  4. 第一个参数不能为指针类型;

空引用也可以调用扩展方法

我们都知道一个为空的对象调用任何方法都会抛出空指针异常,但是如果使用扩展方法却不会这样,如下:

 1 using System;
 2 
 3 namespace Study
 4 {
 5     class Program
 6     {
 7         private static void Main(string[] args)
 8         {
 9             string str = null;
10             Console.WriteLine(str.IsNull());
11 
12             Console.Read();
13         }
14     }
15 
16     public static class MyExtensions
17     {
18         public static bool IsNull(this object obj)
19         {
20             return obj == null;
21         }
22     }
23 }

运行会返回“True”。

原文地址:https://www.cnblogs.com/hammerc/p/4608360.html