扩展方法的 3 个要求:

  1. 声明扩展方法的类必须声明为​​static​​;
  2. 扩展方法本身必须声明为​​static​​;
  3. 扩展方法第一个参数类型前一定要包含关键字​​this​​。
using System;

namespace ExtensionMethods
{
sealed public class MyMethod
{
private double d1, d2, d3;
public MyMethod(double i,double j, double k)
{
d1 = i;
d2 = j;
d3 = k;
}
public double SumMethod()
{
return d1 + d2 + d3;
}
}

static public class ExtensionMythod // [1]、静态类
{
static public double DivdMethos(this MyMethod md) // [2]、静态方法; [3]、第一个参数 this 关键字
{
return md.SumMethod() / 3;
}
}

public class Program
{
static void Main(string[] str)
{
MyMethod md = new MyMethod(3, 4, 5);
double reslut = md.DivdMethos(); // 方法一调用
Console.WriteLine("{0:f2}" , reslut);

reslut = ExtensionMythod.DivdMethos(md); // 方法二调用
Console.WriteLine("{0:f2}", reslut);

Console.ReadKey();
}
}
}

输出:

4.00
4.00

​MyMethod​​​类 和 ​​ExtensionMythod​​​ 类的访问等级要一样,都为 ​​public​​​ 或者 都为 ​​internal​​。

扩展方法也可以跟泛型结合起来使用。



参考: 《图解教程》 -> P145, P322